且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

matplotlib show() 方法不打开窗口

更新时间:2022-06-21 23:29:39

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

Pyplot will only pop up a figure window if

matplotlib.rcParams['interactive'] == True

如果您是这种情况,

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

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

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 before displaying the figure (which is a blocking call).

编辑(问题修改后):

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

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.

如果这是您的问题,则可以添加

If this is your problem, you may add lines like

import matplotlib
matplotlib.use('MacOSX')

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

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

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

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().