What is %pylab?

%pylab is a magic function in ipython.

Magic functions in ipython always begin with the percent sign (%) followed without any spaces by a small text string; in essence, ipython magic functions define shortcuts particularly useful for interactive work, e.g., to give you an idea of how magic functions work in python, a few of my favorites:

  • to view cwd directory contents:

    %ls   
    
  • to run a script in ipython using an empty namespace, type space then a script name:

    %run     
    
  • to execute a code snippet (particularly for multi-line snippets which would usually cause an _IndentationError_ to be thrown):

    %paste
    

When the %pylab magic function is entered at the IPython prompt, it triggers
the import of various modules within Matplotlib.

Which modules? well, the ones subsumed under the pylab interface.

The awesome Matplotlib plotting library has two distinct interfaces: a pythonic one, and the original MATLAB-like one intended for plotting at the interactive prompt.

The former is usually imported like so:

from matplotlib import pyplot as PLT

Indeed, pyplot has its own magic python magic function

%pyplot

Why two different interfaces? Matplotlib’s original interface was pylab; only
later was the pythonic interface added. Scripting and app development were not
the primary uses cases for Matplotlib when the project began, plotting in the
python shell was.

Apparently John Hunter (Matplotlib’s creator) wanted to include interactive plotting in python so he submitted a patch to Fernando Perez’s (FP) IPython project. FP was a Ph.D student at the time and informed JH that he would not able to review the path for some time. As a result, JH created Matplotlib. The significance is that Matplotlib began as a shell-based plotting scheme.

the pylab interface is indeed more suitable for interactive work:

from pylab import *

x, y = arange(10), cos(x/2)
plot(x, y)
show()

and using the pyplot interface:

from matplotlib import pyplot as PLT
import numpy as NP

x, y = NP.arange(10), NP.cos(x/2)
fig = PLT.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y)
PLT.show()

Leave a Comment