UserWarning: Matplotlib is currently using agg,matplotlib图像无法显示问题

1、问题

在virtualenv建立的虚拟环境中,无法用matplotlib来显示图像,程序运行正常,但是提示警告信息:UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure。

2、原因

经过查阅,大体确认是matplotlib的backend(后端)设置有问题,后端就是一个渲染器,用于将前端代码渲染成我们想要的图像。我们可以查看一下目前的后端设置。在python的shell中或者是ipython中执行下面代码。

import matplotlib
matplotlib.get_backend()

我的显示是“agg",agg不能将图像渲染出来的,所以需要设置为其他的,我这里设置为TkAgg。

3、解决办法

安装依赖库,重新进入虚拟环境将matplotlib卸载,再安装,我的没有重新安装就能出图了。

sudo apt-get install tcl-dev tk-dev python-tk python3-tk
pip uninstall matplotlib
pip install matplotlib

python-tk是针对python2的,python3-tk是针对python3的,自行决定安装。

4、查看

再次查看后端设置。
UserWarning: Matplotlib is currently using agg,matplotlib图像无法显示问题_第1张图片

5、测试代码。

UserWarning: Matplotlib is currently using agg,matplotlib图像无法显示问题_第2张图片
测试成功,问题解决。

你可能感兴趣的:(UserWarning: Matplotlib is currently using agg,matplotlib图像无法显示问题)