如何在 Python/Jupyter 笔记本中省略 matplotlib 打印输出? [英] How do I omit matplotlib printed output in Python / Jupyter notebook?
问题描述
当我在 IPython/Jupyter 笔记本中绘制一个简单的图时,会打印输出,大概是从 matplotlib 标准输出生成的.例如,如果我运行下面的简单脚本,笔记本将打印如下一行:
.
When I make a simple plot inside an IPython / Jupyter notebook, there is printed output, presumably generated from matplotlib standard output. For example, if I run the simple script below, the notebook will print a line like: <matplotlib.text.Text at 0x115ae9850>
.
import random
import pandas as pd
%matplotlib inline
A = [random.gauss(10, 5) for i in range(20) ]
df = pd.DataFrame( { 'A': A} )
axis = df.A.hist()
axis.set_title('Histogram', size=20)
如下图所示,即使我没有打印
任何东西,输出也会出现.如何删除或阻止该行?
As you can see in the figure below, the output appears even though I didn't print
anything. How can I remove or prevent that line?
推荐答案
出现此输出是因为 Jupyter 自动打印单元格中最后一个对象的表示.在这种情况下,输入单元格 #1 的最后一行中确实有一个对象.这是对 .set_title(...)
调用的返回值,它是 .Text
类型的实例.此实例返回到笔记本的全局命名空间并因此打印.
This output occurs since Jupyter automatically prints a representation of the last object in a cell. In this case there is indeed an object in the last line of input cell #1. That is the return value of the call to .set_title(...)
, which is an instance of type .Text
. This instance is returned to the global namespace of the notebook and is thus printed.
为了避免这种行为,您可以按照评论中的建议,通过在行尾附加一个分号来抑制输出,这适用于 notebook v6.3.0
, jupyter_core v4.7.1
和 jupyterlab v3.0.14
:
To avoid this behaviour, you can, as suggested in the comments, suppress the output by appending a semicolon to the end of the line, which works as of notebook v6.3.0
, jupyter_core v4.7.1
, and jupyterlab v3.0.14
:
axis.set_title('Histogram', size=20);
另一种方法是将 Text
分配给变量,而不是将其返回到笔记本.因此,
Another approach would assign the Text
to variable instead of returning it to the notebook. Thus,
my_text = axis.set_title('Histogram', size=20)
也解决了问题.
最后,把 plt.show()
放在最后.
Finally, put plt.show()
last.
...
axis.set_title('Histogram', size=20)
plt.show()
这篇关于如何在 Python/Jupyter 笔记本中省略 matplotlib 打印输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!