quot;UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.quot; when plotting figure with pyplot on Pycharm(“用户警告:Matplotlib 当前正在使用 agg,这是一个非 GUI 后端,因此无法显示该图.在 Pycharm 上用 pyplot 绘制图形时) - IT屋-程序员
问题描述
我正在尝试使用 pyplot 绘制一个简单的图形,例如:
I am trying to plot a simple graph using pyplot, e.g.:
import matplotlib.pyplot as plt
plt.plot([1,2,3],[5,7,4])
plt.show()
但该图没有出现,我收到以下消息:
but the figure does not appear and I get the following message:
UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
我在几个地方看到必须使用以下命令更改 matplotlib 的配置:
I saw in several places that one had to change the configuration of matplotlib using the following:
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
我这样做了,但随后收到一条错误消息,因为它找不到模块:
I did this, but then got an error message because it cannot find a module:
ModuleNotFoundError: No module named 'tkinter'
然后,我尝试使用 pip install tkinter
安装tkinter"(在虚拟环境中),但没有找到:
Then, I tried to install "tkinter" using pip install tkinter
(inside the virtual environment), but it does not find it:
Collecting tkinter
Could not find a version that satisfies the requirement tkinter (from versions: )
No matching distribution found for tkinter
我还应该提到,我使用虚拟环境在 Pycharm 社区版 IDE 上运行所有这些,并且我的操作系统是 Linux/Ubuntu 18.04.
I should also mention that I am running all this on Pycharm Community Edition IDE using a virtual environment, and that my operating system is Linux/Ubuntu 18.04.
我想知道如何解决这个问题以便能够显示图表.
推荐答案
解决方案一:安装GUI后端tk
我找到了解决问题的方法(感谢 ImportanceOfBeingErnest 的帮助).
我所要做的就是使用以下命令通过 Linux bash 终端安装 tkinter
:
All I had to do was to install tkinter
through the Linux bash terminal using the following command:
sudo apt-get install python3-tk
而不是使用 pip
或直接在 Pycharm 的虚拟环境中安装.
instead of installing it with pip
or directly in the virtual environment in Pycharm.
- 解决方案 1 可以正常工作,因为您有一个 GUI 后端...在这种情况下是
TkAgg
- 不过,您也可以通过安装任何 matplolib GUI 后端(如
Qt5Agg
、GTKAgg
、Qt4Agg
等)来解决此问题- 例如
pip install pyqt5
也会解决这个问题
- solution 1 works fine because you get a GUI backend... in this case the
TkAgg
- however you can also fix the issue by installing any of the matplolib GUI backends like
Qt5Agg
,GTKAgg
,Qt4Agg
, etc- for example
pip install pyqt5
will fix the issue also
注意:
- 通常当您 pip install matplotlib 并且您尝试在 GUI 窗口中显示绘图并且您没有用于 GUI 显示的 python 模块时会出现此错误.
matplotlib
的作者使 pypi 软件部门不依赖任何 GUI 后端,因为有些人需要matplotlib
没有任何 GUI 后端.
- usually this error appears when you pip install matplotlib and you are trying to display a plot in a GUI window and you do not have a python module for GUI display.
- The authors of
matplotlib
made the pypi software deps not depend on any GUI backend because some people needmatplotlib
without any GUI backend.
这篇关于“用户警告:Matplotlib 当前正在使用 agg,这是一个非 GUI 后端,因此无法显示该图."在 Pycharm 上用 pyplot 绘制图形时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
- for example
- 例如