python之matplotlib中plt.show()不显示图的解决办法

问题

最近,我重新安装了ubuntu,使用virtualenv安装了matplotlib。然后,问题来了。当我运行下列代码时,没有图框跳出来。
<code>
import matplotlib.pyplot as plt
plt.show()
plt.bar(left = 0,height = 1)
</code>

原因

我使用%pylab查看matplotlib后端,发现居然是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 #这是最关键的
</code>

2. 设置agg

其实经过上面的步骤,已经可以画图了
补充2种设置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可以正常工作了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容