Bren
Bren

Reputation: 3706

Error displaying a matplotlib in ipython notebook

I'm going though a ipython notebook tutorial and it says to run this in a cell. import numpy as np import math import matplotlib.pyplot as plt

x = np.linspace(0, 2*math.pi) 
plt.plot(x, np.sin(x), label=r'$\sin(x)$') 
plt.plot(x, np.cos(x), 'ro', label=r'$\cos(x)$') 
plt.title(r'Two plots in a graph') 
plt.legend() 

and I should get an actual graph. Isntead I get

<matplotlib.legend.Legend at 0x1124a2fd0>

What should I do instead?

Upvotes: 0

Views: 1150

Answers (1)

Svend
Svend

Reputation: 7218

Try to add this statement earlier in your notebook, which indicates to matplotlib where to render the plot (i.e. as an html element embedded in the notebook):

%matplotlib inline

The story behind that is simply that matplotlib is old enough to be existing since before jupyter and ipython notebooks became popular. Back then the standard way of creating a plot was to write a script, run it, and obtain an image file as result. Currently the same image can be easily and directly visible in the notebook, at the cost of the supplementary "rewiring" statement above.

In order to display any plot in the notebook, you can have the plot statement as last line of that block code (i.e. the plot is then the returned value, which get rendered by jupyter automatically), or use plt.show() as described by Abdou in the comment.

Also, watch out that you have 2 plots in your code:

# Put these 2 in two separate notebook blocks to get 2 separate plots.
# As-is the first one will never get displayed
plt.plot(x, np.sin(x), label=r'$\sin(x)$') 
plt.plot(x, np.cos(x), 'ro', label=r'$\cos(x)$') 

If you want to have all plots rendered as one single image (which quickly gets hairy with matplotlib imho), have a look at subplot documentation

To make the result prettier, include a ;at the end of the plot to avoid the ugly <matplotlib.legend.Legend at 0x1124a2fd0>

Upvotes: 4

Related Questions