我运行以下代码,用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多次无法显示相同的数字。我该如何避免这种行为?
答案 0 :(得分:0)
问题是我如何用空图处理窗户。我总是在执行fig = plt.figure()
后立即关闭它。我不应该这样做。保持打开允许ax.plot()
在打开的数字上绘制线条。