我试图用pyplot绘制一个简单的图形,例如:

import matplotlib.pyplot as plt
plt.plot([1,2,3],[5,7,4])
plt.show()

但是这个图没有出现,我得到了以下消息:

UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.

我在几个地方看到必须使用以下命令更改matplotlib的配置:

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

我这样做了,但得到了一个错误消息,因为它找不到一个模块:

ModuleNotFoundError: No module named 'tkinter'

然后,我尝试使用pip install tkinter(在虚拟环境中)安装“tkinter”,但它没有找到它:

Collecting tkinter
  Could not find a version that satisfies the requirement tkinter (from versions: )
No matching distribution found for tkinter

我还应该提到,我是在使用虚拟环境的Pycharm Community Edition IDE上运行所有这些,并且我的操作系统是Linux/Ubuntu 18.04。

我想知道我如何解决这个问题,以便能够显示图形。


当前回答

如果使用Jupyter笔记本电脑尝试以下:

%matplotlib inline

这应该呈现的情节,即使没有指定

plt.show()

命令。

其他回答

对我有效的解决方案是:

安装tkinter 将tkinter导入模块 确保matplotlib使用(TkAgg)而不是(Agg) matplotlib.use(“TkAgg”)

issue = "用户警告:Matplotlib目前正在使用agg,这是非gui后端,所以不能显示图形。"

这对我很有效

import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Qt5Agg')

另一个选择是安装Anaconda。这是一个有用的软件,你可以创建许多环境,并且已经安装了许多用于数据科学和机器学习的库。

——编辑

这里有一些步骤可以帮助我解决你同样的问题:

第一步:在官方页面Anaconda下载。exe,使用个人版,因为它是免费的Anaconda个人版 步骤2:一旦你安装了程序,打开到env部分

在本节中,您可以根据自己的喜好创建多个env,例如,我有两个env,一个用于我的主基础(根),一个用于python的最后一个版本。

步骤3:在本节中创建py env, Anaconda将自动安装开发人员使用的主要库,降低代码出错的风险。 额外的考虑:正如你在下面的快照中看到的,你可以很容易地看到你在conda中安装了哪些库。我得到了你同样的错误,因为我错过了3个libs中的一个

希望是有用的和清楚的理解! 自保”

After upgrading lots of packages (Spyder 3 to 4, Keras and Tensorflow and lots of their dependencies), I had the same problem today! I cannot figure out what happened; but the (conda-based) virtual environment that kept using Spyder 3 did not have the problem. Although installing tkinter or changing the backend, via matplotlib.use('TkAgg) as shown above, or this nice post on how to change the backend, might well resolve the problem, I don't see these as rigid solutions. For me, uninstalling matplotlib and reinstalling it was magic and the problem was solved.

pip uninstall matplotlib

... 然后,安装

pip install matplotlib

综上所述,这可能是一个包管理问题,顺便说一句,只要可行,我就同时使用conda和pip。

答案已经给出了几次,但并不明显,一个需要安装图形,这是有效的。

pip3 install PyQt5