26

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

1
  • 2
    Four years after asking this question, the solution I've been using is simply assigning the return value to _, as in _ = axis.set_title(...). Commented Sep 1, 2021 at 22:08

1 Answer 1

29

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer, where on earth is the ' semicolon' solution documented?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.