【问题标题】:How can I show the same matplotlib figure multiple times in IPython shell?如何在 IPython shell 中多次显示相同的 matplotlib 图形?
【发布时间】:2018-03-07 08:51:25
【问题描述】:

我运行以下代码,使用 matplotlib 面向对象的 API 绘制单行。

$ ipython --pylab
In [1]: fig = plt.figure() # An empty figure is shown in popped up window here
In [2]: ax = fig.add_subplot(1,1,1)
In [3]: ax.plot(arange(10)) # no figure is shown up here
Out[3]: [<matplotlib.lines.Line2D at 0x7fb134118400>]
In [4]: fig.show()

fig = plt.figure() 执行时,会弹出新窗口,并显示一个空图。通过ax.plot(arange(10))绘制后,没有自动显示图形,所以我尝试通过fig.show()显示图形,我得到了这个错误。

AttributeError                            Traceback (most recent call last)
<ipython-input-6-6ebedab27258> in <module>()
----> 1 fig.show()

~/.pyenv/versions/3.6.4/envs/analysis/lib/python3.6/site-packages/matplotlib/figure.py in show(self, warn)
    409         if manager is not None:
    410             try:
--> 411                 manager.show()
    412                 return
    413             except NonGuiException:

~/.pyenv/versions/3.6.4/envs/analysis/lib/python3.6/site-packages/matplotlib/backends/backend_tkagg.py in show(self)
    560             self.canvas.draw_idle()
    561         # Raise the new window.
--> 562         self.canvas.manager.window.attributes('-topmost', 1)
    563         self.canvas.manager.window.attributes('-topmost', 0)
    564         self._shown = True

AttributeError: 'NoneType' object has no attribute 'attributes'

但是像这样一个丑陋的单线正确地显示了一个折线图。

plt.figure().add_subplot(1,1,1).plot(arange(10))

IPython shell 似乎无法多次显示同一个图形。如何避免这种行为?

【问题讨论】:

  • 如果您处于交互模式(听起来像是),那么您不需要致电show()。 ax.plot()应该更新图
  • 感谢您的评论。我还期望ax.plot() 显示更新后的数字,但事实并非如此。更新了问题以澄清这一点。

标签: python matplotlib ipython jupyter


【解决方案1】:

问题是我如何处理带有空图的窗户。我总是在执行fig = plt.figure() 后立即关闭它。我不应该这样做。保持打开状态允许ax.plot() 在打开的图形上画线。

【讨论】:

    猜你喜欢
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 2016-05-23
    • 2020-02-22
    • 2016-02-24
    • 1970-01-01
    相关资源
    最近更新 更多