如何在Python/Jupyter笔记本中省略matplotlib打印输出? [英] How do I omit matplotlib printed output in Python / Jupyter notebook?
问题描述
当我在IPython/Jupyter笔记本中进行简单绘图时,会显示打印输出,大概是从matplotlib标准输出生成的.例如,如果我运行以下简单脚本,则笔记本将打印如下一行:<matplotlib.text.Text at 0x115ae9850>
.
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)
如下图所示,即使我没有print
,也不会出现输出.如何删除或阻止该行?
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 occures 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.
为避免此行为,您可以按照注释中的建议,通过在行的末尾添加分号来禁止输出:
To avoid this behaviour, you can, as suggested in the comments, suppress the output by appending a semicolon to the end of the line:
axis.set_title('Histogram', size=20);
另一种方法是将Text
分配给变量,而不是将其返回到笔记本.因此,
The other approach would assign the Text
to variable istead of returning it to the notebook. Thus,
my_text = axis.set_title('Histogram', size=20)
也解决了这个问题.
这篇关于如何在Python/Jupyter笔记本中省略matplotlib打印输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!