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?
Press 'control-shift-p', that opens the command palette. Then type 'clear cell output'. That will let you select the command to clear the output.
Capturing Output With %%capture IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable. By default, %%capture discards these streams. This is a simple way to suppress unwanted output.
Avoid Display With ioff() Method We can turn the interactive mode off using matplotlib. pyplot. ioff() methods. This prevents figure from being displayed.
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.
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);
Another approach would assign the Text
to variable instead of returning it to the notebook. Thus,
my_text = axis.set_title('Histogram', size=20)
solves the problem as well.
Finally, put plt.show()
last.
...
axis.set_title('Histogram', size=20)
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With