我试图用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。

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


当前回答

对于Windows 10,如果使用pip install tk不适合你,请尝试:

下载并运行官方的python安装程序。即使你 已经下载好了,再运行一次。 当(重新)安装python时,确保您选择了“高级”选项,并且 将“tcl/tk and IDLE”复选框设置为true。 如果你已经安装了python,选择“修改”选项,然后 确保选中了复选框。

修复方法的来源: https://stackoverflow.com/a/59970646/2506354

其他回答

Try:

%matplotlib inline

我也遇到过同样的问题,这招对我很管用。我在我的Jupyter笔记本和visual studio代码上测试了它,所以你应该没有问题。

小心你的代码中的导入顺序,我花了一整天的时间通过这个答案,最终通过在其他任何东西之前导入bt,然后使用.use('TkAgg')语句解决了问题(由于某种原因,导入bt将matplotlib后端更改为'Agg')

对我有效的解决方案是:

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

在使用Pycharm专业版2021.3时,这些答案对我都不起作用

常规的matplotlib图表在科学观点上确实有效,但它不允许我向图表中添加图像。

对我来说有用的是在我尝试绘制任何东西之前添加这条线:

plt switch_backend (TkAgg’)。

Ubuntu 20.04命令行设置。我安装了以下程序,以使Matplotlib停止抛出错误UserWarning: Matplotlib目前正在使用agg,这是非gui后端,因此无法显示图形。

我通过以下步骤安装python-tk:

apt-get update

apt-get install python3.8-tk