Matplotlib的“交互模式”(ion(),ioff())的精确语义?

2024-04-28 04:16:36 发布

您现在位置:Python中文网/ 问答频道 /正文

Matplotlib的pyplot中的“交互模式”文档如下:

The interactive property of the pyplot interface controls whether a figure canvas is drawn on every pyplot command. If interactive is False, then the figure state is updated on every plot command, but will only be drawn on explicit calls to draw(). When interactive is True, then every pyplot command triggers a draw.

这似乎很清楚:当交互模式打开时,可以不必做plot()就可以做draw()。但是,在以下代码中执行draw()不会执行任何操作:

from matplotlib import pyplot as pp

# Interactive mode is off by default

pp.plot([10, 20, 50])
pp.draw()

raw_input('Press enter...')  # No graph displayed?!!

(在Windows XP上,Matplotlib 1.0.1)。

在开始处添加ion()将使图形出现,同时等待用户键入enter(这将方便地关闭所有图形):

from matplotlib import pyplot as pp

ion()

pp.plot([10, 20, 50])  # No draw() is necessary

raw_input('Press enter...')  # The graph is interactive *and* the terminal responds to enter

因此,看起来ion()比在每个绘图命令后添加自动图形更新的更多,而且很遗憾,我在文档中找不到任何内容。后一个程序的另一个更重要的问题是,ion()使所有plot命令更新图形,这在一个图形多次更新时非常耗时。

那么,有没有办法:

  • 让终端等待输入,然后所有数字自动关闭
  • 具有交互式Matplotlib图
  • …而不强制在开始时启用交互模式(以便不强制自动更新图形,这可能会很耗时)?

Tags: the图形plotmatplotlibison模式command
2条回答

下面是Matplotlib邮件列表中有关此主题的interesting discussion摘要。执行摘要如下:

  • 交互模式(通过ion()激活)自动化了许多事情。尤其是,pyplot.*命令会在屏幕上自动更新相关轴。但是,对Matplotlib对象(如ax.plot()ax是Axes对象)的方法调用通常不执行自动更新;在这种情况下,pyplot.draw()执行必要的更新。

  • 非交互模式不太方便。draw()通常不更新屏幕上的图形。在非交互模式下,draw()有点“不活动”的事实在当前文档中没有提到,但希望很快会包含在其中。

同时,在Matplotlib的a current branch中可以找到更多关于交互模式和非交互模式的信息。一个更好的documentation对于draw()show()和朋友也可以在同一个分支中找到。

我建议你听“托马斯K”的最后一句话。我记得邮件列表上有一个类似的问题,但经过几分钟的搜索,我还是找不到。对不起的。

我也有这个问题,对我来说更好的方法是使用ipython --pylab。我安装了一个旧得多的matplotlib版本,它在ion()方面有一些问题。除此之外,matplotlib在Windows上的draw()也有一些问题。也许它是在上一个版本中修复的。

附言:很抱歉我帮不了你。

谨致问候。

相关问题 更多 >