Ubuntu14.04 64位+Python3.4环境下安装matplotlib的方法

时间:2023-02-04 06:32:01

问题:

具体的问题是这样的:
我的系统是Ubuntu14.04 的64位系统,python3.4版本下,想使用matplotlib来做图。
由于matplotlib依赖numpy和python的图像库PIL,因此我先安装numpy和PIL然后,再安装matplotlib,

这里附上我的安装matplotlib的shell命令

#安装科学计算库numpy
sudo pip3 install numpy
#安装图像处理库PIL
sudo apt-get install python3.4-dev -y
sudo apt-get install libjpeg8-dev zlib1g-dev libfreetype6-dev -y
sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib
sudo apt-get install python3-pil
#安装画图库matplotlib
sudo pip3 install matplotlib

但是发现虽然安装成功(在python3的shell交互环境下, import matplotlib 是可以的),但是 执行如下语句
from matplotlib import pyplot as plt

报错:
"/usr/local/lib/python3.4/dist-packages/matplotlib-1.5.1-py3.4-linux-x86_64.egg/matplotlib/backends/backend_gtk3.py", line 58, in 
cursors.MOVE : Gdk.Cursor.new(Gdk.CursorType.FLEUR),
TypeError: constructor returned NULL


解决方法:

首先安装python3-dev,再安装numpy,再安装PIL,最后把安装matplotlib的命令前面加上相关依赖库的命令

sudo apt-get install libfreetype6-dev libxft-dev -y

并将命令

sudo pip3 install matplotlib 

替换为

sudo apt-get install python3-matplotlib -y

下面附上最终正确安装的shell脚本


#!/bin/bash
sudo apt-get update
sudo apt-get install python3-pip -y
#安装科学计算库numpy
sudo apt-get install python3.4-dev -y
sudo pip3 install numpy
#安装图像处理库PIL
sudo apt-get install python3.4-dev -y
sudo apt-get install libjpeg8-dev zlib1g-dev libfreetype6-dev -y
sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib
sudo apt-get install python3-pil -y
#安装画图库matplotlib
sudo apt-get install libfreetype6-dev libxft-dev -y
sudo apt-get install python3-matplotlib -y
#sudo pip3 install matplotlib


如果后面使用中还出现错误,请参照下面的解决办法:

解决方法网址: https://www.zhihu.com/question/46560194/answer/101967730?group_id=717491965033218048

作者:gao xinge
链接:https://www.zhihu.com/question/46560194/answer/101967730
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

如你所述
from matplotlib import pyplot as plt
可能会报错,而且有时还可能会出现如下的错误[2]
import matplotlib.pyplot as plt
fig = plt.figure()
无论哪种形式,原因都是缺少X server,因此无法画一个窗体(windows)。所以你可以选择别的方式,来取代默认的输出,比如
import matplotlib
matplotlib.use('Agg') # or matplotlib.use("Pdf")
import matplotlib.pyplot as plt
但是要注意中间那句的位置一定是放另外两句话之间的,否则会报错,参见[3]

[1] python - TypeError constructor returned NULL while importing pyplot in ssh
[2] python - Generating matplotlib graphs without a running X server
[3] python - Generating a PNG with matplotlib when DISPLAY is undefined