Auxillary tutorial 2: Saving a figure using matplotlib

This auxillary tutorial was generated from an IPython notebook. You can download the notebook here.

In [1]:
# Stuff we always import
from __future__ import print_function, division
import numpy as np
import matplotlib.pyplot as plt

# Inline for the purposes of making this document
%matplotlib inline

# And an ODE integrator for our fun curve
import scipy.integrate

After you make a figure in Python, it is important to save it so you can use it in other applications, such as putting it in presentations or manuscripts. matplotlib has an easy way to do this using plt.savefig.

We will first generate something cool to plot (a plot of the Lorentz attractor, just for fun), and then save the figure. You can skip the details of this, since it is just for fun (the lesson of this handout being how to save a figure).

The Lorentz attractor is described by a system of ordinary differential equations

\begin{align} \frac{\mathrm{d}x}{\mathrm{d}t} & = s(y-x) \\ \frac{\mathrm{d}y}{\mathrm{d}t} & = x(p-z) - y \\ \frac{\mathrm{d}z}{\mathrm{d}t} & = xy - bz. \end{align}

For certain sets of parameters $(s, p, b)$, the solution to the Lorentz attractor exhibits chaotic trajectories, which is why it is fun. We will plot a projection of the trajectory onto the $x$-$y$ plane.

In [26]:
"""
This is a bunch of code to generate a Lorentz attractor that you can skip
and go on to saving the fiture.
"""
def lorentz_attractor(r, t, p):
    """
    Right hand side of system of ODEs describing Lorentz attractor.
    x' = s * (y - x)
    y' = x * (p - z) - y
    z' = x * y - b * z
    
    The input r is (x, y, z) and p is (s, p, b).  
    
    t is time and must be present for odeint to work, but not explicit
    in computation of the Lorentz attractor ODE.
    """
    x, y, z = r
    s, p, b = p
    return np.array([s * (y - x), x * (p - z) - y, x * y - b * z])

# Parameters to use
p = np.array([10.0, 28.0, 8.0 / 3.0])

# Initial condition
r0 = np.array([0.1, 0.0, 0.0])

# Time points to sample
t = np.linspace(0.0, 80.0, 10000)

# Use scipy.integrate.odeint to integrate Lorentz attractor
r = scipy.integrate.odeint(lorentz_attractor, r0, t, args=(p,))

# Unpack results into x, y, z.
x, y, z = r.transpose()

We have just used SciPy to integrate the dynamical equations of the Lorentz attractor. We can now plot a 2D projection onto the $x$-$z$ plane.

We can save the fiture in various formats. The plt.savefig function will parse your output file name and save your figure accordingly.

I like to use the bbox_inches='tight keyword argument because it deletes all of the whitespace around the plot. I also like the transparent=True keyword argument, especially if I want to use the plot in a presentation where I want the background color of the plot to be the same as the slide background.

In [28]:
# Plot a 2D projection of the Lorentz attractor trajectory
plt.plot(x, z, 'k-', linewidth=0.5)
plt.xlabel(r'$x(t)$')
plt.ylabel(r'$z(t)$')
plt.title(r'$x$-$z$ proj. of Lorentz attractor traj.')

# This will save the figure as a PDF
plt.savefig('lorentz.pdf', bbox_inches='tight', transparent=True)

# This will save it as a scalable vector graphics (SVG) file
plt.savefig('lorentz.svg', bbox_inches='tight', transparent=True)

# This will save it as an encapsulated postscript (EPS) file
plt.savefig('lorentz.eps', bbox_inches='tight', transparent=True)

If you are using Canopy, you can also save your figure by clicking on the disk image on the figure window. The problem with doing this is that you do not have as much control of the output settings as you do using the keyword arguments of plt.savefig.

Note also that I saved the figure as PDF, SVG, and EPS. These are vector graphics. I could have saved it as a PNG, JPEG, or some other raster graphics format. With the exceptions of images themselves, almost all of the plots you will display in this course and in research should use vector graphics. A set of axes and a plot of points are mathematical objects. Their resolution should not change if we zoom in.

You will find the literature is rife with examples of rasterized plots. This is not good.