Plotting with Matplotlib

Prepare for action


In [1]:
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 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')



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

In [11]:
# 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 [12]:
plt.plot(x,x**2)
#Write code to show grid in plot here


Out[12]:
[<matplotlib.lines.Line2D at 0x7fde08dd7ad0>]
  • change the location of the legend to different places

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


Out[13]:
<matplotlib.legend.Legend at 0x7fde08c76250>

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


Out[14]:
[<matplotlib.lines.Line2D at 0x7fde09d42d90>]
  • add different sub-plots

In [ ]:
fig, ax = plt.subplots(nrows=1, ncols=1)
ax.plot(x,x**2)
  • 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)
  • use twinx() to create a second axis on the right for the second plot

In [ ]:
plt.plot(x,x**2)
plt.plot(x,x**4, 'r')
  • add horizontal and vertical lines using axvline(), axhline()

In [ ]:
plt.plot(x,x**2)
  • autoformat dates for nice printing on the x-axis using fig.autofmt_xdate()

In [ ]:
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)

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 [ ]:

  • create a vector y, so that y=sin(x) with some random noise

In [ ]:

  • plot it like this:

In [ ]:

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 [ ]:


In [ ]: