Plotting with Pylab and Matplotlib¶
IPython works with the Matplotlib plotting library using the the Pylab mode, which integrates Matplotlib with IPython's display system and event loop handling.
Pylab mode¶
To make plots using Matplotlib, you must first enable IPython's Pylab mode. There are two ways of doing this:
- You can give the
--pylab
command line argument when starting the IPython Notebook Server, to enable plotting in all Notebooks automatically. - You can run the
%pylab
magic command to enable plotting in the current Notebook.
Both commands take an optional argument that specifies which Matplotlib backend should be used. Most of the time, in the Notebook, you will want to use the inline
backend, which will embed plots inside the Notebook:
%pylab inline
The equivalent command line argument would be --pylab inline
.
You can also use Matplotlib GUI backends in the Notebook, such as the Qt backend (%pylab qt
). This will use Matplotlib's interactive Qt UI in a floating window to the side of your browser. Of course, this only works if your browser is running on the same system as the Notebook Server. You can always call the display
function to paste figures into the Notebook document.
Making a simple plot¶
With Pylab enabled, plotting should just work.
x = linspace(0, 3*pi, 500)
plot(x, sin(x**2))
title('A simple chirp');
These images can be resized by dragging the handle in the lower right corner. Double clicking will return them to their original size.
One thing to be aware of is that by default, the Figure
object is cleared at the end of each cell, so you will need to issue all plotting commands for a single figure in a single cell.
Loading Matplotlib demos using %load¶
IPython's %load
magic can be used to load any Matplotlib demo by its URL:
%load http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/integral_demo.py
#!/usr/bin/env python
# implement the example graphs/integral from pyx
from pylab import *
from matplotlib.patches import Polygon
def func(x):
return (x-3)*(x-5)*(x-7)+85
ax = subplot(111)
a, b = 2, 9 # integral area
x = arange(0, 10, 0.01)
y = func(x)
plot(x, y, linewidth=1)
# make the shaded region
ix = arange(a, b, 0.01)
iy = func(ix)
verts = [(a,0)] + zip(ix,iy) + [(b,0)]
poly = Polygon(verts, facecolor='0.8', edgecolor='k')
ax.add_patch(poly)
text(0.5 * (a + b), 30,
r"$\int_a^b f(x)\mathrm{d}x$", horizontalalignment='center',
fontsize=20)
axis([0,10, 0, 180])
figtext(0.9, 0.05, 'x')
figtext(0.1, 0.9, 'y')
ax.set_xticks((a,b))
ax.set_xticklabels(('a','b'))
ax.set_yticks([])
show()