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

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


当前回答

在Mac OS上,我让它工作:

import matplotlib
matplotlib.use('MacOSX')

其他回答

Linux Mint 19。对我有帮助:

sudo apt install tk-dev

附注:安装包后重新编译python解释器。

这个问题的解决方法是: 确保把这条线放好

%matplotlib inline

在代码头部

像这样

# In an IPython notebook¶
# This magic just sets up matplotlib's interactive mode
%matplotlib inline
# So you have to explicitely import the module into the namespace
import matplotlib.pyplot as pl
import numpy as np
# Create the figure object
fig = pl.figure(figsize=(12, 8))
x = np.arange(0, 4 * np.pi, 0.1)
y = np.sin(x)
pl.plot(x, y)

%matplotlib inline turns on “inline plotting”, where plot graphics will appear in your notebook. This has important implications for interactivity: for inline plotting, commands in cells below the cell that outputs a plot will not affect the plot. For example, changing the color map is not possible from cells below the cell that creates a plot. However, for other backends, such as qt4, that open a separate window, cells below those that create the plot will change the plot - it is a live object in memory. If you are not using matplotlib in interactive mode at all, figures will only appear if you invoke

有关%matplotlib内联的更多信息,请参阅此链接

在Mac OS上,我让它工作:

import matplotlib
matplotlib.use('MacOSX')

Try:

%matplotlib inline

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

我在Windows 7和PyCharm Pro上也遇到过同样的问题。 它发生在我安装金融软件包“ffn”之后

import ffn

Matplotlib后端更改为“add”。 你可以检查当前后端:

matplotlip.get_backend()

您可以通过以下方式更改当前后端:

matplotlib.use(backend = "module://backend_interagg")

这在一个额外的或内部窗口中为我的PyCharm Professional解决了问题。