如何在IPython notebook中隐藏<matplotlib.lines.Line2D>

70 投票
3 回答
24086 浏览
提问于 2025-04-21 02:51

我正在使用IPython笔记本,在%matplotlib内联模式下绘制一个NumPy数组的值I,命令是plt.plot(I,'o')

执行后得到的结果是:

<matplotlib.figure.Figure at 0x119e6ead0>
Out[159]:
[<matplotlib.lines.Line2D at 0x11ac57090>,
 <matplotlib.lines.Line2D at 0x11ac57310>,
 <matplotlib.lines.Line2D at 0x11ac57510>,
 <matplotlib.lines.Line2D at 0x11ac57690>,
 <matplotlib.lines.Line2D at 0x11ac57810>,
 <matplotlib.lines.Line2D at 0x11ac57990>,
 <matplotlib.lines.Line2D at 0x11ac57b10>,
 ....
 ....
]

然后我的图表会显示在这些输出的下面。

有没有办法只显示图表,而不显示<matplotlib.lines.Line2D at ...>这样的输出呢?

3 个回答

0

这是个老问题...
我个人更喜欢在最后一行用一个 pass

虽然它不像 ; 那么简短,但在我看来,它更容易看懂,而且也不算长。

23

另一种方法是在你绘图代码的最后写上 plt.show()。如果你要生成很多子图或者在一个子图上画很多图,这样写会更省事,输入的字符也会少一些。

118

你可以用分号 ; 来结束一行代码。这样可以避免在生成图表时出现不必要的输出:

plt.plot(I,'o');

一般来说,使用分号可以阻止 IPython 打印出那行代码的输出结果。例如,执行包含代码 1+1; 的单元格时,就不会输出 2

另一种方法是将图表绑定到一个变量上:

_ = plt.plot(a)

这样,IPython 只会显示图表,而名称 _ 则绑定了不需要的输出。

撰写回答