Python matplotlib show() 方法不打开窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21835847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:42:28  来源:igfitidea点击:

matplotlib show() method does not open window

pythonmatplotlibshow

提问by toom

I'm using a mac and when I do the following with matplotlib:

我使用的是 mac,当我使用 matplotlib 执行以下操作时:

import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import pylab as P

...
plt.plot(x,y)  
plt.show() <-- nothing happens
plt.savefig('figure.png') <-- works fine

So, plt.showdoes not open a window or anything while plt.savefigworks fine.

因此,plt.showplt.savefig工作正常时不打开窗口或任何东西。

What could be the problem?

可能是什么问题呢?

采纳答案by wim

Pyplot will only pop up a figure window if

Pyplot 只会弹出一个图形窗口,如果

matplotlib.rcParams['interactive'] == True

This is the case if you:

如果您是这种情况:

  • have previous called plt.ion()in your script, or
  • equivalently, called matplotlib.interactive(True), or
  • started an ipython session with the --pylaboption at the command line.
  • 之前plt.ion()在您的脚本中调用过,或者
  • 等效地,称为matplotlib.interactive(True),或
  • 使用--pylab命令行中的选项启动了 ipython 会话。

When interactive mode is off, you generally have to call plt.show()explicitly to make the figure window pop up. This is because we often want to call plot multiple times to draw various things beforedisplaying the figure (which is a blocking call).

当交互模式关闭时,您通常必须plt.show()显式调用才能弹出图形窗口。这是因为我们经常想显示图形之前多次调用 plot 来绘制各种东西(这是一个阻塞调用)。



Edit (after the question was modified):

编辑(修改问题后)

One reason for plt.show()not popping up a figure window is that you haven't activated an interactive backend. Check the output of plt.get_backend()- if it returns 'agg', for example, you have a non-interactive backend.

plt.show()不弹出图形窗口的原因之一是您尚未激活交互式后端。检查输出plt.get_backend()- 如果它返回'agg',例如,您有一个非交互式后端。

If this is your problem, you may add lines like

如果这是您的问题,您可以添加类似的行

import matplotlib
matplotlib.use('MacOSX')

At the start of your script to specify the backend. This needs to be placed before any other matplotlib related imports.

在脚本的开头指定后端。这需要放在任何其他与 matplotlib 相关的导入之前。

To make such a change permanent, you can specify a different backend as default by modifying your matplotlib rcfile. The location of this file is found by calling matplotlib.matplotlib_fname().

要使这种更改永久化,您可以通过修改 matplotlib rcfile 将不同的后端指定为默认值。这个文件的位置是通过调用找到的matplotlib.matplotlib_fname()