What is %pylab?
Question:
I keep seeing people use %pylab
in various code snippits, particularly with iPython. However, I cannot see where %pylab
is mentioned anywhere in Learning Python (and the few other Python books I have) and am not really sure what it means.
I’m sure the answer is simple, but can anyone enlighten me?
Answers:
As its name implies, Pylab is a MATLABlike front end for doing mathematics in Python. iPython has specific support for Pylab, which is invoked using the %pylab
magic command.
%pylab
is a “magic function” that you can call within IPython, or Interactive Python. By invoking it, the IPython interpreter will import matplotlib
and NumPy
modules such that you’ll have convenient access to their functions. As an example,
rich@richubuntu:~/working/fb_recruit/working$ ipython
Python 2.7.6 Anaconda 1.8.0 (64bit) (default, Nov 11 2013, 10:47:18)
Type "copyright", "credits" or "license" for more information.
IPython 1.1.0  An enhanced Interactive Python.
? > Introduction and overview of IPython's features.
%quickref > Quick reference.
help > Python's own help system.
object? > Details about 'object', use 'object??' for extra details.
In [1]: arange(4)

NameError Traceback (most recent call last)
<ipythoninput12e43d7eb1b3e> in <module>()
> 1 arange(4)
NameError: name 'arange' is not defined
In [2]: %pylab
Using matplotlib backend: Qt4Agg
Populating the interactive namespace from numpy and matplotlib
In [3]: arange(4)
Out[3]: array([0, 1, 2, 3])
In [4]:
%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 multiline 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 MATLABlike 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 shellbased 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()
%pylab
is a shortcut for typing all of the below commands – in essence adding numpy and matplotlib into your session. This was incorporated in iPython as a transition tool and the current recommendation is that you should not use it. The core reason is that the below sets of commands import too much into the global namespace and also they don’t allow you to change the mode for matplotlib from UI to QT or something else. You can see tje history and reasoning behind this at http://nbviewer.ipython.org/github/Carreau/posts/blob/master/10NoPyLabThanks.ipynb?create=1.
This is what %pylab
does:
import numpy
import matplotlib
from matplotlib import pylab, mlab, pyplot
np = numpy
plt = pyplot
from IPython.core.pylabtools import figsize, getfigs
from pylab import *
from numpy import *
This is what I use instead at the start of my notebook:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
More recent documentation about the IPython magics here.
Magics function are often present in the form of shelllike syntax,
but are under the hood python function. The syntax and assignment
possibility are similar to the one with the bang (!) syntax, but with
more flexibility and power. Magic function start with a percent sign
(%) or double percent (%%).
A little bit here and more specifically about the %pylab
magic here.
%pylab [noimportall] [gui]
Load numpy and matplotlib to work interactively.
This function lets you activate pylab (matplotlib, numpy and
interactive support) at any point during an IPython session.
%pylab
makes the following imports:
import numpy
import matplotlib
from matplotlib import pylab, mlab, pyplot
np = numpy
plt = pyplot
from IPython.display import display
from IPython.core.pylabtools import figsize, getfigs
from pylab import *
from numpy import *