Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I omit matplotlib printed output in Python / Jupyter notebook? [duplicate]

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 notebook output

like image 469
stackoverflowuser2010 Avatar asked Aug 04 '17 23:08

stackoverflowuser2010


People also ask

How do I get rid of output in Jupyter Notebook?

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.

What does %% capture do in Jupyter?

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.

How do I stop Matplotlib from showing?

Avoid Display With ioff() Method We can turn the interactive mode off using matplotlib. pyplot. ioff() methods. This prevents figure from being displayed.


1 Answers

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()
like image 67
MaxPowers Avatar answered Oct 18 '22 00:10

MaxPowers