本文介绍了matplotlib show() 方法不打开窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using a mac and when I do the following with 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

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

So, plt.show does not open a window or anything while plt.savefig works fine.

可能是什么问题?

推荐答案

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

这篇关于matplotlib show() 方法不打开窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 01:54