Plotting with Matplotlib

Prepare for action


In [2]:
import numpy as np
import scipy as sp
import sympy

# Pylab combines the pyplot functionality (for plotting) with the numpy
# functionality (for mathematics and for working with arrays) in a single namespace
# aims to provide a closer MATLAB feel (the easy way). Note that his approach
# should only be used when doing some interactive quick and dirty data inspection.
# DO NOT USE THIS FOR SCRIPTS
#from pylab import *

# the convienient Matplotib plotting interface pyplot (the tidy/right way)
# use this for building scripts. The examples here will all use pyplot.
import matplotlib.pyplot as plt

# for using the matplotlib API directly (the hard and verbose way)
# use this when building applications, and/or backends
import matplotlib as mpl

How would you like the IPython notebook show your plots? In order to use the matplotlib IPython magic youre IPython notebook should be launched as

ipython notebook --matplotlib=inline

Make plots appear as a pop up window, chose the backend: 'gtk', 'inline', 'osx', 'qt', 'qt4', 'tk', 'wx'

%matplotlib qt

or inline the notebook (no panning, zooming through the plot). Not working in IPython 0.x

%matplotib inline

In [3]:
# activate pop up plots
#%matplotlib qt
# or change to inline plots
#%matplotlib inline
%matplotlib


Using matplotlib backend: module://IPython.kernel.zmq.pylab.backend_inline

Matplotlib documentation

Finding your own way (aka RTFM). Hint: there is search box available!

The Matplotlib API docs:

Pyplot, object oriented plotting:

Extensive gallery with examples:

Tutorials for those who want to start playing

If reading manuals is too much for you, there is a very good tutorial available here:

Note that this tutorial uses

from pylab import *

which is usually not adviced in more advanced script environments. When using

import matplotlib.pyplot as plt

you need to preceed all plotting commands as used in the above tutorial with

plt.

Give me more!

EuroScipy 2012 Matlotlib tutorial. Note that here the author uses from pylab import *. When using import matplotliblib.pyplot as plt the plotting commands need to be proceeded with plt.

Plotting template starting point


In [4]:
# some sample data
x = np.arange(-10,10,0.1)

To change the default plot configuration values.


In [5]:
page_width_cm = 13
dpi = 200
inch = 2.54 # inch in cm
# setting global plot configuration using the RC configuration style
plt.rc('font', family='serif')
plt.rc('xtick', labelsize=12) # tick labels
plt.rc('ytick', labelsize=20) # tick labels
plt.rc('axes', labelsize=20)  # axes labels
# If you don’t need LaTeX, don’t use it. It is slower to plot, and text
# looks just fine without. If you need it, e.g. for symbols, then use it.
plt.rc('text', usetex=True) #<- P-E: Doesn't work on my Mac

In [6]:
# create a figure instance, note that figure size is given in inches!
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8,6))
# set the big title (note aligment relative to figure)
fig.suptitle("suptitle 16, figure alignment", fontsize=16)

# actual plotting
ax.plot(x, x**2, label="label 12")


# set axes title (note aligment relative to axes)
ax.set_title("title 14, axes alignment", fontsize=14)

# axes labels
ax.set_xlabel('xlabel 12')
ax.set_ylabel(r'$y_{\alpha}$ 12')

# legend
ax.legend(fontsize=12, loc="best")

# saving the figure in different formats
fig.savefig('figure-%03i.png' % dpi, dpi=dpi)
fig.savefig('figure.svg')
fig.savefig('figure.eps')


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-6-9e34228444af> in <module>()
     21 fig.savefig('figure-%03i.png' % dpi, dpi=dpi)
     22 fig.savefig('figure.svg')
---> 23 fig.savefig('figure.eps')

C:\Python27\lib\site-packages\matplotlib\figure.pyc in savefig(self, *args, **kwargs)
   1419             self.set_frameon(frameon)
   1420 
-> 1421         self.canvas.print_figure(*args, **kwargs)
   1422 
   1423         if frameon:

C:\Python27\lib\site-packages\matplotlib\backend_bases.pyc in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2218                 orientation=orientation,
   2219                 bbox_inches_restore=_bbox_inches_restore,
-> 2220                 **kwargs)
   2221         finally:
   2222             if bbox_inches and restore_bbox:

C:\Python27\lib\site-packages\matplotlib\backend_bases.pyc in print_eps(self, *args, **kwargs)
   1945         from backends.backend_ps import FigureCanvasPS  # lazy import
   1946         ps = self.switch_backends(FigureCanvasPS)
-> 1947         return ps.print_eps(*args, **kwargs)
   1948 
   1949     def print_pdf(self, *args, **kwargs):

C:\Python27\lib\site-packages\matplotlib\backends\backend_ps.pyc in print_eps(self, outfile, *args, **kwargs)
    979 
    980     def print_eps(self, outfile, *args, **kwargs):
--> 981         return self._print_ps(outfile, 'eps', *args, **kwargs)
    982 
    983     def _print_ps(self, outfile, format, *args, **kwargs):

C:\Python27\lib\site-packages\matplotlib\backends\backend_ps.pyc in _print_ps(self, outfile, format, *args, **kwargs)
   1003             self._print_figure_tex(outfile, format, imagedpi, facecolor, edgecolor,
   1004                                    orientation, isLandscape, papertype,
-> 1005                                    **kwargs)
   1006         else:
   1007             self._print_figure(outfile, format, imagedpi, facecolor, edgecolor,

C:\Python27\lib\site-packages\matplotlib\backends\backend_ps.pyc in _print_figure_tex(self, outfile, format, dpi, facecolor, edgecolor, orientation, isLandscape, papertype, **kwargs)
   1360             if False: pass # for debugging
   1361             else: gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox,
-> 1362                              rotated=psfrag_rotated)
   1363 
   1364         is_file = False

C:\Python27\lib\site-packages\matplotlib\backends\backend_ps.pyc in gs_distill(tmpfile, eps, ptype, bbox, rotated)
   1507 
   1508     gs_exe = ps_backend_helper.gs_exe
-> 1509     if ps_backend_helper.supports_ps2write: # gs version >= 9
   1510         device_name = "ps2write"
   1511     else:

C:\Python27\lib\site-packages\matplotlib\backends\backend_ps.pyc in supports_ps2write(self)
    106         True if the installed ghostscript supports ps2write device.
    107         """
--> 108         return self.gs_version[0] >= 9
    109 
    110 ps_backend_helper = PsBackendHelper()

C:\Python27\lib\site-packages\matplotlib\backends\backend_ps.pyc in gs_version(self)
     96         else:
     97             ver = pipe.read()
---> 98         gs_version = tuple(map(int, ver.strip().split(".")))
     99 
    100         self._cached["gs_version"] = gs_version

ValueError: invalid literal for int() with base 10: ''

In [ ]:
ax.grid(True)
fig.canvas.draw()

In [ ]:
# following steps are only relevant when using figures as pop up windows (with %matplotlib qt)
# to update a figure with has been modified
fig.canvas.draw()
# show a figure
fig.show()

Exercise

The current section is about you trying to figure out how to do several plotting features. You should use the previously mentioned resources to find how to do that. In many cases, google is your friend!

  • add a grid to the plot

In [ ]:
plt.plot(x,x**2)
#Write code to show grid in plot here
plt.grid()
  • change the location of the legend to different places

In [ ]:
plt.plot(x,x**2, label="label 12")
plt.legend(fontsize=12, loc="best")

In [ ]:
plt.plot(x,x**2, label="label 12")
plt.legend(fontsize=12, loc="lower right")

In [ ]:
plt.plot(x,x**2, label="label 12")
plt.legend(fontsize=12, loc="center")

In [ ]:
plt.plot(x,x**2, 'o-')
  • add different sub-plots

In [ ]:
plt.plot(x,x**2, 'r-')

In [ ]:
plt.plot(x,x**2, 'g+')

In [ ]:
plt.plot(x,x**2, 'bo', markevery = 10)

In [ ]:
fig, ax = plt.subplots(nrows=1, ncols=2)
ax[0].plot(x,x**2)
ax[1].plot(x,x**2, 'r')
  • size the figure such that when included on an A4 page the fonts are given in their true size

In [ ]:

  • make a contour plot

In [ ]:
X, Y = np.meshgrid(x,x)
Z = X**3+Y**3

cnt = plt.contour(Z, vmin=abs(Z).min(), vmax=abs(Z).max(), extent=[0, 1, 0, 1])
  • use twinx() to create a second axis on the right for the second plot

In [7]:
fig, ax1 = plt.subplots()
ax1.plot(x,x**2)
ax2 = ax1.twinx()
ax2.plot(x,x**3, 'r')


Out[7]:
[<matplotlib.lines.Line2D at 0x8bc74f0>]
  • add horizontal and vertical lines using axvline(), axhline()

In [8]:
plt.plot(x,x**2)
plt.plot(x,x**2)
plt.axvline(x=0, ymin=0, ymax=1)
plt.axhline(y=50, xmin=-10, xmax=10)


Out[8]:
<matplotlib.lines.Line2D at 0x8abf8b0>
  • autoformat dates for nice printing on the x-axis using fig.autofmt_xdate()

In [9]:
import datetime
dates = np.array([datetime.datetime.now() + datetime.timedelta(days=i) for i in xrange(24)])
fig, ax = plt.subplots(nrows=1, ncols=1)
ax.bar(dates, np.random.rand(24))
fig.autofmt_xdate(bottom=0.2, rotation=30, ha='right')


Advanced exercises

We are going to play a bit with regression

  • Create a vector x of equally spaced number between $x \in [0, 5\pi]$ of 1000 points (keyword: linspace)

In [10]:
x = np.linspace(0, 5*np.pi, 1000)
  • create a vector y, so that y=sin(x) with some random noise

In [11]:
y = np.sin(x)+(np.random.random(1000)-0.5)
  • plot it like this:

In [12]:
fig, ax = plt.subplots(1, 1)
ax.plot(x, y, '.')
ax.plot(x, np.sin(x), 'k--', linewidth=3, label='y=sin(x)')

ax.legend(loc =1)


Out[12]:
<matplotlib.legend.Legend at 0x8f34dd0>

Try to do a polynomial fit on y(x) with different polynomial degree (Use numpy.polyfit to obtain coefficients)

Plot it like this (use np.poly1d(coef)(x) to plot polynomials)


In [14]:
fig, ax = plt.subplots(1, 1)
ax.plot(x, y, '.')
ax.plot(x, np.sin(x), 'k--', linewidth=3, label='y=sin(x)')

for i in range(0, 10):
    coeff = np.polyfit(x, y, i)
    ax.plot(x, np.polyval(coeff, x), label='deg=%i'%i)

ax.legend(loc=7, bbox_to_anchor=(1.32, 0.5))


Out[14]:
<matplotlib.legend.Legend at 0xa2abff0>

In [ ]: