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

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


当前回答

如果在项目中使用一些第三方代码,则有效。它可能包含以下一行

matplotlib.use('Agg')

搜索它并注释掉它。

如果您不知道它是什么,那么您可能不会使用这部分代码。

使用另一个后端GUI的解决方案可能更干净,所以选择你的战斗机。

其他回答

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

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

apt-get update

apt-get install python3.8-tk

我在PyCharm中也遇到了这个问题。这个问题是因为您的机器中没有tkinter模块。

按照下面给出的步骤安装(选择合适的操作系统)

对于ubuntu用户

 sudo apt-get install python-tk

or

 sudo apt-get install python3-tk

对于Centos用户

 sudo yum install python-tkinter

or

 sudo yum install python3-tkinter

适用于Arch用户

  sudo pacman -S tk

or

  sudo pamac install tk

Windows操作系统使用pip安装tk

安装tkinter后,重新启动Pycharm并运行代码,它将工作

这适用于R网状结构。在这里找到的。

1: matplotlib。使用“tkaggs” 前 2: matplotlib$use('tkagg')

例如:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style

import matplotlib
matplotlib.use( 'tkagg' )


style.use("ggplot")
from sklearn import svm

x = [1, 5, 1.5, 8, 1, 9]
y = [2, 8, 1.8, 8, 0.6, 11]

plt.scatter(x,y)
plt.show()

我已经通过将matplotlib.use('TkAgg')放在所有导入语句之后解决了这个问题。 我使用python 3.8.5 VSCODE和anaconda。 其他花招都没用。

对我有效的解决方案是:

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