Plotting with Matplotlib

Prepare for action


In [1]:
import numpy as np
import scipy as sp
import sympy
import pylab as plb

# 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 [2]:
# activate pop up plots
#%matplotlib qt
# or change to inline plots
%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 [3]:
# some sample data
x = np.arange(-10,10,0.1)

To change the default plot configuration values.


In [4]:
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=12) # 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 [5]:
# 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', fontsize=8)

# 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')


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-5-ed6225f3f625> in <module>()
     20 # saving the figure in different formats
     21 fig.savefig('figure-%03i.png' % dpi, dpi=dpi)
---> 22 fig.savefig('figure.svg')
     23 fig.savefig('figure.eps')

C:\Anaconda\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:\Anaconda\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:\Anaconda\lib\site-packages\matplotlib\backend_bases.pyc in print_svg(self, *args, **kwargs)
   1976         from backends.backend_svg import FigureCanvasSVG  # lazy import
   1977         svg = self.switch_backends(FigureCanvasSVG)
-> 1978         return svg.print_svg(*args, **kwargs)
   1979 
   1980     def print_svgz(self, *args, **kwargs):

C:\Anaconda\lib\site-packages\matplotlib\backends\backend_svg.pyc in print_svg(self, filename, *args, **kwargs)
   1155         else:
   1156             raise ValueError("filename must be a path or a file-like object")
-> 1157         return self._print_svg(filename, svgwriter, fh_to_close, **kwargs)
   1158 
   1159     def print_svgz(self, filename, *args, **kwargs):

C:\Anaconda\lib\site-packages\matplotlib\backends\backend_svg.pyc in _print_svg(self, filename, svgwriter, fh_to_close, **kwargs)
   1183                     bbox_inches_restore=_bbox_inches_restore)
   1184 
-> 1185             self.figure.draw(renderer)
   1186             renderer.finalize()
   1187         finally:

C:\Anaconda\lib\site-packages\matplotlib\artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     53     def draw_wrapper(artist, renderer, *args, **kwargs):
     54         before(artist, renderer)
---> 55         draw(artist, renderer, *args, **kwargs)
     56         after(artist, renderer)
     57 

C:\Anaconda\lib\site-packages\matplotlib\figure.pyc in draw(self, renderer)
   1032         dsu.sort(key=itemgetter(0))
   1033         for zorder, a, func, args in dsu:
-> 1034             func(*args)
   1035 
   1036         renderer.close_group('figure')

C:\Anaconda\lib\site-packages\matplotlib\artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     53     def draw_wrapper(artist, renderer, *args, **kwargs):
     54         before(artist, renderer)
---> 55         draw(artist, renderer, *args, **kwargs)
     56         after(artist, renderer)
     57 

C:\Anaconda\lib\site-packages\matplotlib\axes.pyc in draw(self, renderer, inframe)
   2084 
   2085         for zorder, a in dsu:
-> 2086             a.draw(renderer)
   2087 
   2088         renderer.close_group('axes')

C:\Anaconda\lib\site-packages\matplotlib\artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     53     def draw_wrapper(artist, renderer, *args, **kwargs):
     54         before(artist, renderer)
---> 55         draw(artist, renderer, *args, **kwargs)
     56         after(artist, renderer)
     57 

C:\Anaconda\lib\site-packages\matplotlib\axis.pyc in draw(self, renderer, *args, **kwargs)
   1094 
   1095         for tick in ticks_to_draw:
-> 1096             tick.draw(renderer)
   1097 
   1098         # scale up the axis label box to also find the neighbors, not

C:\Anaconda\lib\site-packages\matplotlib\artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     53     def draw_wrapper(artist, renderer, *args, **kwargs):
     54         before(artist, renderer)
---> 55         draw(artist, renderer, *args, **kwargs)
     56         after(artist, renderer)
     57 

C:\Anaconda\lib\site-packages\matplotlib\axis.pyc in draw(self, renderer)
    234                 self.gridline.draw(renderer)
    235             if self.tick1On:
--> 236                 self.tick1line.draw(renderer)
    237             if self.tick2On:
    238                 self.tick2line.draw(renderer)

C:\Anaconda\lib\site-packages\matplotlib\artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     53     def draw_wrapper(artist, renderer, *args, **kwargs):
     54         before(artist, renderer)
---> 55         draw(artist, renderer, *args, **kwargs)
     56         after(artist, renderer)
     57 

C:\Anaconda\lib\site-packages\matplotlib\lines.pyc in draw(self, renderer)
    620                     renderer.draw_markers(gc, marker_path, marker_trans,
    621                                           subsampled, affine.frozen(),
--> 622                                           rgbaFace)
    623 
    624                 alt_marker_path = marker.get_alt_path()

C:\Anaconda\lib\site-packages\matplotlib\backends\backend_svg.pyc in draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace)
    587         trans_and_flip = self._make_flip_transform(trans)
    588         attrib = {u'xlink:href': u'#%s' % oid}
--> 589         for vertices, code in path.iter_segments(trans_and_flip, simplify=False):
    590             if len(vertices):
    591                 x, y = vertices[-2:]

C:\Anaconda\lib\site-packages\matplotlib\path.pyc in iter_segments(self, transform, remove_nans, clip, snap, stroke_width, simplify, curves, sketch)
    398                                snap=snap, stroke_width=stroke_width,
    399                                simplify=simplify, curves=curves,
--> 400                                sketch=sketch)
    401         vertices = cleaned.vertices
    402         codes = cleaned.codes

C:\Anaconda\lib\site-packages\matplotlib\path.pyc in cleaned(self, transform, remove_nans, clip, quantize, simplify, curves, stroke_width, snap, sketch)
    437                                              remove_nans, clip,
    438                                              snap, stroke_width,
--> 439                                              simplify, curves, sketch)
    440         internals = {'should_simplify': self.should_simplify and not simplify,
    441                      'has_nonfinite': self.has_nonfinite and not remove_nans,

IndexError: Unexpected SeqBase<T> length.

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


C:\Anaconda\lib\site-packages\matplotlib\figure.py:371: UserWarning: matplotlib is currently using a non-GUI backend, so cannot show the figure
  "matplotlib is currently using a non-GUI backend, "

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 [7]:
plt.plot(x,x**2)
#Write code to show grid in plot here
axx = plt.gca();
axx.grid(b=True,which='major',color='r',linestyle='-',linewidth=0.25)


  • change the location of the legend to different places

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


Out[8]:
<matplotlib.legend.Legend at 0xb8d8630>

In [9]:
#plt.plot(x,x**2, 'o-')
plt.plot(x,x**2,'o-',color='r',linestyle='-',linewidth=0.75,markersize=8,markevery=10)


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

In [10]:
fig, ax = plt.subplots(nrows=3, ncols=1, sharex=True)
ax1=ax[0].plot(x,x**2)
fontsizze=9;
ax[1].plot(x,x**7)
ax[2].plot(x,x**4)
for i in range(0, 2):
    ax[i]
    axx = plt.gca();
    for tick in axx.yaxis.get_major_ticks():
        tick.label.set_fontsize(fontsizze)
        
#for (tx, ty) in zip(axx.xaxis.get_major_ticks(), axx.yaxis.get_major_ticks()):
#    tx.label.set_fontsize(4)
#    ty.label.set_fontsize(14)
figg = plt.figure(figsize = (5.5, 4.3))
#figg.subplots_adjust(hspace = 0.005)
sal_ax = plt.subplot(3,1,1)
sal_ax.plot(x,x**2)
sal_ax = plt.subplot(3,1,2)
sal_ax.plot(x,x**7)
sal_ax = plt.subplot(3,1,3)
sal_ax.plot(x,x**4)

for i in range(2, 4):
    plt.subplot(3,1,i)
    axx = plt.gca();
    for tick in axx.yaxis.get_major_ticks():
        tick.label1.set_fontsize(fontsizze)


  • size the figure such that when included on an A4 page the fonts are given in their true size

In [11]:
fig, ax = plt.subplots(nrows=2, ncols=1, sharex=True)
ax[0].plot(x,x**2)
ax[1].plot(x,x**7)
f = plt.gcf()
f.set_size_inches(8.27,11.69)


  • make a contour plot

In [12]:
X, Y = np.meshgrid(x,x)
Z = X**2+Y
plt.contourf(X,Y,Z)
plt.colorbar()


Out[12]:
<matplotlib.colorbar.Colorbar instance at 0x000000000C8D71C8>
  • use twinx() to create a second axis on the right for the second plot

In [13]:
ax =plt.plot(x,x**2)
axx=plt.plot(x,x**4, 'r')
plt.twinx()


Out[13]:
<matplotlib.axes.AxesSubplot at 0xca01da0>
  • add horizontal and vertical lines using axvline(), axhline()

In [14]:
plt.plot(x,x**2,'r')
plt.axvline(5)
plt.axhline(75)


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

In [16]:
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)
#for i in range(1,24):
#    print dates[i]
ax.plot(dates,xrange(24),'o')
plt.gcf().autofmt_xdate()


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 [233]:
xx=np.array(np.linspace(0,5*np.pi,1000))
  • create a vector y, so that y=sin(x) with some random noise

In [234]:
#print xx.shape()
print len(xx)
y=np.sin(xx)+np.random.uniform(-1, 1, size=len(xx))


1000
  • plot it like this:

In [235]:
plt.plot(xx,y,'bo',markersize=8,markevery=3)
plt.plot(xx,np.sin(xx),'k-',linewidth=4,label="y=sin(x)")
plt.legend(fontsize=12,loc='best')


Out[235]:
<matplotlib.legend.Legend at 0x192d6048>

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 [237]:
#a= [i for i in range (0,10)];
#b= [i for i in range (0,len(xx))];
z=np.zeros((10,10));
z1=np.zeros((len(xx),10));
for i in range(0,10):
    #print i
    z[0:i+1,i]=np.polyfit(xx, y, i)

In [250]:
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(xx,y,'bo',markersize=8,markevery=2)
ax.plot(xx,np.sin(xx),'k-',linewidth=5,label="y=sin(x)")
for i in range (0,10):
    ax.plot(xx,np.poly1d(z[0:i+1,i])(xx),linewidth=2,label=('deg='+str(i)))
    
handles, labels = ax.get_legend_handles_labels()
lgd = ax.legend(handles, labels, fontsize=12,loc='upper left', bbox_to_anchor=(1.02, 1), borderaxespad=0)
#ax.legend(fontsize=11,loc='upper right')



In [ ]:


In [ ]: