問題
最近,我重新安裝了ubuntu,使用virtualenv安裝了matplotlib。然后,問題來了。當(dāng)我運(yùn)行下列代碼時,沒有圖框跳出來。
<code>
import matplotlib.pyplot as plt
plt.show()
plt.bar(left = 0,height = 1)
</code>
原因
我使用%pylab查看matplotlib后端,發(fā)現(xiàn)居然是agg。兄弟姐妹們,agg是不會畫圖的!
<code>
In [4]:%pylab
Using matplotlib backend: agg
Populating the interactive namespace from numpy and matplotlib
</code>
解決
1. 安裝Tkinter 和 matplotlib
我的問題在于我原來的python居然沒有Tkinter!!
<code>
sudo apt-get install tk-dev
pip uninstall -y matplotlib
pip --no-cache-dir install -U matplotlib #這是最關(guān)鍵的
</code>
2. 設(shè)置agg
其實(shí)經(jīng)過上面的步驟,已經(jīng)可以畫圖了
補(bǔ)充2種設(shè)置agg方法
臨時的
<code>
import matplotlib
matplotlib.use('TkAgg')
</code>
這個命令必須在第一次使用%pylab 或者import matplotlib.pyplot as plt之前使用
常見的agg有:Qt4Agg Qt5Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG永久的
修改matplotlibrc文件
matplotlibrc文件的位置在:
<code>[~/.virtualenvs/myenv]/lib/python2.7/site-packages/matplotlib/mpl-data/</code>
修改位置:
<code>
backend : youragg
</code>
至此,matplotlib可以正常工作了。