Plotting

One of the biggest advantages of the notebook format is that you can mix code and plots.

In this example we'll draw some simple mathematical functions using matplotlib.

Setup

The first thing you need to do is tell the kernel that you would like to use matplotlib to make plots.

You do this using the magic invocation:

%matplotlib inline

The inline option means that plots will appear directly in the output cell of the notebook. Later in this notebook we'll try other options.


In [1]:
%matplotlib inline

Draw a plot

Next we'll draw a plot using the standard matplotlib commands. We'll use the pyplot module which has a similar interface to MATLAB and Octave for plotting.

See the official matplotlib page for documentation on matplotlib and examples.


In [2]:
from matplotlib import pyplot as plt

x = [1, 2, 3]
y = [2, 4, 3]
plt.plot(x, y);


Prettier plot

Matplotlib has many options for making pretty plots. Here is an example of a simulated damped oscillator. In this example we're using numpy to generate and keep track of the numerical data.

Demo source: http://matplotlib.org/users/screenshots.html


In [3]:
"""
Simple demo with multiple subplots.
"""
import numpy as np
import matplotlib.pyplot as plt


x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'yo-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')

plt.subplot(2, 1, 2)
plt.plot(x2, y2, 'r.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')
plt.show()


Size

To change the size of plots you can use the regular matplotlib commands. Here is a very small cosine plot.


In [4]:
"""
Tiny cosine plot.
"""
import numpy as np
from matplotlib import pyplot as plt

x = np.linspace(0, 10)
y = np.cos(x)
plt.figure(figsize=(2, 2))
plt.plot(x, y);



In [5]:
"""
Large cosine plot.
"""
import numpy as np
from matplotlib import pyplot as plt

x = np.linspace(0, 10)
y = np.cos(x)
plt.figure(figsize=(10, 10))
plt.plot(x, y);


Large inline plots are scaled down to fit the notebook width. Plots smaller than the width are not resized.

Windowed Plots

You can also let matplotlib create plots in a new window so that you can independently resize and interact with the plot. Here is the cosine example in a new window.


In [1]:
"""
Windowed cosine plot.
"""
%matplotlib osx

import numpy as np
from matplotlib import pyplot as plt

x = np.linspace(0, 10)
y = np.cos(x)
#plt.figure(figsize=(10, 10))
plt.plot(x, y);


---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-096d61b1ae9c> in <module>()
      2 Windowed cosine plot.
      3 """
----> 4 get_ipython().magic(u'matplotlib osx')
      5 
      6 import numpy as np

/home/nwhitehead/projects/pineapple/build/share/Pineapple/pineapple-server/IPython/core/interactiveshell.pyc in magic(self, arg_s)

/home/nwhitehead/projects/pineapple/build/share/Pineapple/pineapple-server/IPython/core/interactiveshell.pyc in run_line_magic(self, magic_name, line)

/home/nwhitehead/projects/pineapple/build/share/Pineapple/pineapple-server/IPython/core/magics/pylab.pyc in matplotlib(self, line)

/home/nwhitehead/projects/pineapple/build/share/Pineapple/pineapple-server/IPython/core/magic.pyc in <lambda>(f, *a, **k)

/home/nwhitehead/projects/pineapple/build/share/Pineapple/pineapple-server/IPython/core/magics/pylab.pyc in matplotlib(self, line)

/home/nwhitehead/projects/pineapple/build/share/Pineapple/pineapple-server/IPython/core/interactiveshell.pyc in enable_matplotlib(self, gui)

/home/nwhitehead/projects/pineapple/build/share/Pineapple/pineapple-server/IPython/core/pylabtools.pyc in activate_matplotlib(backend)

/home/nwhitehead/projects/pineapple/build/venv/src/pyinstaller/PyInstaller/loader/pyi_importers.py in load_module(self, fullname, path)
    269 
    270                 # Run the module code.
--> 271                 exec(bytecode, module.__dict__)
    272                 # Reread the module from sys.modules in case it's changed itself
    273                 module = sys.modules[fullname]

/home/nwhitehead/projects/pineapple/build/share/Pineapple/pineapple-server/matplotlib/pyplot.pyc in <module>()

/home/nwhitehead/projects/pineapple/build/share/Pineapple/pineapple-server/matplotlib/backends/__init__.pyc in pylab_setup()

/home/nwhitehead/projects/pineapple/build/venv/src/pyinstaller/PyInstaller/loader/pyi_importers.py in load_module(self, fullname, path)
    269 
    270                 # Run the module code.
--> 271                 exec(bytecode, module.__dict__)
    272                 # Reread the module from sys.modules in case it's changed itself
    273                 module = sys.modules[fullname]

/home/nwhitehead/projects/pineapple/build/share/Pineapple/pineapple-server/matplotlib/backends/backend_macosx.pyc in <module>()

ImportError: cannot import name _macosx

Note that plot windows are not saved as part of the notebook like inline plots are. You will have to execute your code again to regenerate the plot when loading the notebook.