Matplotlib 2015


In [1]:
%matplotlib inline 
from pylab import *
from matplotlib.pyplot import *

Above commands enable pylab environment => direct access to numpy, scipy and matplotlib. The option 'inline' results in plot outputs to be directly embedded in the Notebook. If this causes problems, remove the option 'inline'.


In [2]:
xv=[1,2,3,4]; yv=[5,1,4,0]
plot(xv,yv)


Out[2]:
[<matplotlib.lines.Line2D at 0x10b7b6d50>]

A simple plotting example. Maybe some variations:


In [3]:
plot(xv,yv,'ro')


Out[3]:
[<matplotlib.lines.Line2D at 0x10b902950>]

In [4]:
myplot=plot(xv,yv,'k--')
setp(myplot,linewidth=3.0,marker='+',markersize=30)


Out[4]:
[None, None, None]

Alternatively, Matplotlib understands the MATLAB syntax, e.g., for the above command (does not work with 'inline' enabled):


In [5]:
myplot=plot(xv,yv,'k--')
setp(myplot,'linewidth',3.0,'marker','+','markersize',30)


Out[5]:
[None, None, None]

Available settings for a plot can be found this way (does not work with 'inline' enabled):


In [6]:
setp(myplot)


  agg_filter: unknown
  alpha: float (0.0 transparent through 1.0 opaque)         
  animated: [True | False]         
  antialiased or aa: [True | False]         
  axes: an :class:`~matplotlib.axes.Axes` instance         
  clip_box: a :class:`matplotlib.transforms.Bbox` instance         
  clip_on: [True | False]         
  clip_path: [ (:class:`~matplotlib.path.Path`,         :class:`~matplotlib.transforms.Transform`) |         :class:`~matplotlib.patches.Patch` | None ]         
  color or c: any matplotlib color         
  contains: a callable function         
  dash_capstyle: ['butt' | 'round' | 'projecting']         
  dash_joinstyle: ['miter' | 'round' | 'bevel']         
  dashes: sequence of on/off ink in points         
  drawstyle: ['default' | 'steps' | 'steps-pre' | 'steps-mid' |                   'steps-post']         
  figure: a :class:`matplotlib.figure.Figure` instance         
  fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top' | 'none']         
  gid: an id string         
  label: string or anything printable with '%s' conversion.         
  linestyle or ls: [``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` |                   ``' '`` | ``''``]
  linewidth or lw: float value in points         
  lod: [True | False]         
  marker: :mod:`A valid marker style <matplotlib.markers>`
  markeredgecolor or mec: any matplotlib color         
  markeredgewidth or mew: float value in points         
  markerfacecolor or mfc: any matplotlib color         
  markerfacecoloralt or mfcalt: any matplotlib color         
  markersize or ms: float         
  markevery: [None | int | length-2 tuple of int | slice |         list/array of int | float | length-2 tuple of float]
  path_effects: unknown
  picker: float distance in points or callable pick function         ``fn(artist, event)``         
  pickradius: float distance in points         
  rasterized: [True | False | None]         
  sketch_params: unknown
  snap: unknown
  solid_capstyle: ['butt' | 'round' |  'projecting']         
  solid_joinstyle: ['miter' | 'round' | 'bevel']         
  transform: a :class:`matplotlib.transforms.Transform` instance         
  url: a url string         
  visible: [True | False]         
  xdata: 1D array         
  ydata: 1D array         
  zorder: any number         

Some more commands for plot formatting:


In [7]:
axis()


Out[7]:
(0.0, 1.0, 0.0, 1.0)

In [8]:
axis([0.5,4.5,-0.5,5.5])


Out[8]:
[0.5, 4.5, -0.5, 5.5]

In [9]:
ti=title('Very important data')
xl=xlabel('time'); yl=ylabel('value')
setp(xl,fontweight='bold')


Out[9]:
[None]

Figures can be saved in a number of output formats such as Postscript:


In [10]:
savefig('foo.ps', dpi=600, format='ps',orientation='landscape')


<matplotlib.figure.Figure at 0x10bd594d0>

Alternatively, you can also save figures in PNG bitmap and PDF vector formats. (Note that some export formats may not be supported on your platform.)


In [11]:
savefig('foo.png', dpi=600, format='png',orientation='landscape')
savefig('foo.pdf', dpi=600, format='pdf',orientation='landscape')


<matplotlib.figure.Figure at 0x10b7f7bd0>

Get a handle to current figure and close it:


In [12]:
myfig=gcf()
close(myfig)

Or in MATLAB style, close all open figures:


In [13]:
close('all')

Let's do a figure with several subpanels:


In [14]:
fig2=figure()
subplot(2,1,1)
plot(xv,yv,'b-')
subplot(2,1,2)
plot(yv,xv,'ro')


Out[14]:
[<matplotlib.lines.Line2D at 0x10bc84f10>]

In [15]:
close(fig2)

Especially for figures with multiple subpanels it may be advisable to increase the figure size somewhat. Do this by using function arguments in the figure() call:


In [16]:
fig2=figure(figsize=(10,10))
subplot(2,1,1)
plot(xv,yv,'b-')
subplot(2,1,2)
plot(yv,xv,'ro')


Out[16]:
[<matplotlib.lines.Line2D at 0x10bd15850>]

By using Numpy arrays, Matplotlib can conveniently be used as a function ploting program:


In [17]:
xv=np.arange(-10,10.5,0.5); xv


Out[17]:
array([-10. ,  -9.5,  -9. ,  -8.5,  -8. ,  -7.5,  -7. ,  -6.5,  -6. ,
        -5.5,  -5. ,  -4.5,  -4. ,  -3.5,  -3. ,  -2.5,  -2. ,  -1.5,
        -1. ,  -0.5,   0. ,   0.5,   1. ,   1.5,   2. ,   2.5,   3. ,
         3.5,   4. ,   4.5,   5. ,   5.5,   6. ,   6.5,   7. ,   7.5,
         8. ,   8.5,   9. ,   9.5,  10. ])

In [18]:
plot(xv,2*xv**3-5*xv**2+7*xv)
plot(xv,2000*cos(xv),'r--')
text(-10,-2800,'curve A')
text(3,1500,'curve B')


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-18-efb02fdfe8fa> in <module>()
      1 plot(xv,2*xv**3-5*xv**2+7*xv)
----> 2 plot(xv,2000*cos(xv),'r--')
      3 text(-10,-2800,'curve A')
      4 text(3,1500,'curve B')

NameError: name 'cos' is not defined

Certainly, you can do plots with logarithmic scale:


In [19]:
close('all'); xv_lin=np.arange(-3,3.01,0.02)
xv=10.**xv_lin
semilogx(xv,exp(-xv/0.01)+0.5*exp(-xv/10)+0.2* exp(-xv/200))


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-19-333f899ba61b> in <module>()
      1 close('all'); xv_lin=np.arange(-3,3.01,0.02)
      2 xv=10.**xv_lin
----> 3 semilogx(xv,exp(-xv/0.01)+0.5*exp(-xv/10)+0.2* exp(-xv/200))

NameError: name 'exp' is not defined

Let's add grid lines:


In [20]:
semilogx(xv,exp(-xv/0.01)+0.5*exp(-xv/10)+0.2* exp(-xv/200))
grid(color='k')


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-20-c98c8691c5e6> in <module>()
----> 1 semilogx(xv,exp(-xv/0.01)+0.5*exp(-xv/10)+0.2* exp(-xv/200))
      2 grid(color='k')

NameError: name 'exp' is not defined

Analogously, you can use semilogy() and loglog() for plots with log y-axis and loglog plots.


In [21]:
semilogy(xv,exp(-xv/0.01)+0.5*exp(-xv/10)+0.2* exp(-xv/200))


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-21-787cb386b53b> in <module>()
----> 1 semilogy(xv,exp(-xv/0.01)+0.5*exp(-xv/10)+0.2* exp(-xv/200))

NameError: name 'exp' is not defined

Anybody bar charts?


In [22]:
close('all')
xv=[0.5,1.5,2.5,3.5]; yv=[2,5,1,6]
mybar=bar(xv, yv, width=1, yerr=0.5)


Let's pimp the plot a little:


In [23]:
mybar=bar(xv, yv, width=1, yerr=0.5)
xticks(xv, ['A','B','C','D'])
setp(mybar, color='r',
edgecolor='k')


Out[23]:
[None, None, None, None, None, None, None, None]

For horizontal bar charts, you would use barh().

Where there are bars, there should be pies:


In [24]:
close('all')
figure(figsize=(5,5))
handles=pie([1,2,3,4], explode=[0.2,0,0,0], shadow=True, labels=['A','B','C','D'])
handles


Out[24]:
([<matplotlib.patches.Wedge at 0x10e860510>,
  <matplotlib.patches.Wedge at 0x10e86e450>,
  <matplotlib.patches.Wedge at 0x10e87d310>,
  <matplotlib.patches.Wedge at 0x10e8891d0>],
 [<matplotlib.text.Text at 0x10e860f10>,
  <matplotlib.text.Text at 0x10e86ee10>,
  <matplotlib.text.Text at 0x10e87dcd0>,
  <matplotlib.text.Text at 0x10e889b90>])

As you will have seen, we retrieved handles to the individual pie slices. Let's do something with them:


In [25]:
figure(figsize=(5,5))
handles=pie([1,2,3,4], explode=[0.2,0,0,0], shadow=True, labels=['A','B','C','D'])
setp(handles[0] [0], color='y')
setp(handles[1] [0], text='Blubber')


Out[25]:
[None]

Matplotlib also offers quiver() plots which are illustrated in the following example (taken from http://www.loria.fr/~rougier/teaching/matplotlib/):


In [26]:
close('all')
n=8; X,Y=np.mgrid[0:n,0:n]
T=np.arctan2(Y-n/2.0,X-n/2.0)
R=10+np.sqrt((Y-n/2.0)**2+(X-n/2.0)**2)
U,V=R*np.cos(T),R*np.sin(T)
axes([0.025,0.025,0.95,0.95])
quiver(X,Y,U,V,R,alpha=.5)
quiver(X,Y,U,V, edgecolor='k', facecolor= 'None', linewidth=.5)
show()


Polar plots are also nicely illustrated on the very same homepage:


In [27]:
close('all')
ax=axes([0.025,0.025,0.95,0.95],polar=True)
N=20; theta=np.arange(0.0,2*np.pi,2*np.pi/N)
radii=10*np.random.rand(N)
width=np.pi/4*np.random.rand(N)
bars=bar(theta,radii,width=width,bottom=0.0)
for r,bar in zip(radii,bars):
    bar.set_facecolor( cm.jet(r/10.))
    bar.set_alpha(0.5)
show()


Contour plots are well suited for visualization of three-dimensional data sets:


In [35]:
close('all')
xv=linspace(-10,10,100); yv=xv
X,Y=meshgrid(xv,yv)
Z=exp(-((X-1)**2/2/0.5**2)-((Y+2)**2/2/3**2))
Z=Z+1.5*exp(-((X-5)**2/2/4**2)-((Y-6)**2/2/3**2))
contourf(X,Y,Z,10,alpha=0.5,cmap=cm.hot)
C=contour(X,Y,Z,10,colors='black', linewidth=0.5)
clabel(C,inline=1,fontsize=10)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-35-a9cc5074618f> in <module>()
      1 close('all')
----> 2 xv=linspace(-10,10,100); yv=xv
      3 X,Y=meshgrid(xv,yv)
      4 Z=exp(-((X-1)**2/2/0.5**2)-((Y+2)**2/2/3**2))
      5 Z=Z+1.5*exp(-((X-5)**2/2/4**2)-((Y-6)**2/2/3**2))

NameError: name 'linspace' is not defined

A similar yet distint representation is provided by pcolormesh().


In [36]:
figure()
pcolormesh(X,Y,Z,alpha=0.5,cmap=cm.hot)
axis([-5,10,-8,10])


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-36-c44fa72b9312> in <module>()
      1 figure()
----> 2 pcolormesh(X,Y,Z,alpha=0.5,cmap=cm.hot)
      3 axis([-5,10,-8,10])

NameError: name 'Z' is not defined

Compare the two figures, spot the similarities and differences.

Matplotlib sports an add-on module for 3D graphics as detailed below. First, we need to import this module.


In [30]:
from mpl_toolkits.mplot3d import Axes3D

Let's switch to the Qt backend for 3D plotting


In [31]:
%matplotlib


Using matplotlib backend: MacOSX

Then, we can play around.


In [32]:
close('all')
fig=figure(); ax=Axes3D(fig)

Try moving and rotating the (so far empty) plot in three dimensions. Once you have calmed down, let's populate the plot with some data:


In [33]:
close('all')
fig=figure(); ax=Axes3D(fig)
import random as rn
xv=[]; yv=[]; zv=[]
for c in range(100):
   xv.append(rn.random()); yv.append(rn.random())
   zv.append(rn.random())
ax.scatter(xv,yv,zv)


Out[33]:
<mpl_toolkits.mplot3d.art3d.Path3DCollection at 0x10f4ae410>

In addition to the above 3D scatter plot, other plot types are supported, such as 3D surface plots:


In [34]:
close('all'); fig=figure()
ax=Axes3D(fig)
xv=linspace(-10,10,100); yv=linspace(-10,10,100)
cx,cy=meshgrid(xv,yv)
cz=0.5*cx+exp(-cy**2)
tilt=ax.plot_surface(cx,cy,cz,linewidth=0, cmap=cm.jet)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-34-d81ae5740388> in <module>()
      1 close('all'); fig=figure()
      2 ax=Axes3D(fig)
----> 3 xv=linspace(-10,10,100); yv=linspace(-10,10,100)
      4 cx,cy=meshgrid(xv,yv)
      5 cz=0.5*cx+exp(-cy**2)

NameError: name 'linspace' is not defined

Try some other colormaps such as cm.bone, cm.spring or cm.cool (once more, these are the MATLAB color schemes).

We do one more example that shows the use of 3D surface and 3D contour plots (as opposed to the 2D contour plots above).


In [37]:
close('all'); fig=figure()
ax=Axes3D(fig)
xv=linspace(-10,10,100); yv=linspace(-10,10,100)
cx,cy=meshgrid(xv,yv)
cz=0*cx

def gauss2D(x0,y0,sigx=1,sigy=1,height=1):
   z=height*exp(-((cx-x0)**2/2/sigx**2)-((cy-y0)**2/2/sigy**2))
   return z

cz=cz+gauss2D(-2,3)
cz=cz+gauss2D(2,4,2,3)
ax.plot_surface(cx,cy,cz,linewidth=0,cstride=2, rstride=2,cmap=cm.jet)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-37-7ee6014a63ba> in <module>()
      1 close('all'); fig=figure()
      2 ax=Axes3D(fig)
----> 3 xv=linspace(-10,10,100); yv=linspace(-10,10,100)
      4 cx,cy=meshgrid(xv,yv)
      5 cz=0*cx

NameError: name 'linspace' is not defined

Let's display the same data in contour representation:


In [38]:
close('all'); fig=figure()
ax=Axes3D(fig)
ax.contour(cx,cy,cz,cstride=2,rstride=2, cmap=cm.jet)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-38-4e7d8c345808> in <module>()
      1 close('all'); fig=figure()
      2 ax=Axes3D(fig)
----> 3 ax.contour(cx,cy,cz,cstride=2,rstride=2, cmap=cm.jet)

NameError: name 'cx' is not defined

Style sheets


In [39]:
%matplotlib inline
close('all')

There are several predefinded style sheets for matplotlib. You can show all availible styles by typing


In [40]:
style.available


Out[40]:
[u'dark_background', u'bmh', u'grayscale', u'ggplot', u'fivethirtyeight']

to pick one of them, type e.g.


In [41]:
style.use('ggplot')

and your plots will look similar to those created with ggplot2 in R


In [42]:
x = np.linspace(0,10,100)
y = np.sin(x)
plot(x,y)


Out[42]:
[<matplotlib.lines.Line2D at 0x10eb4bc10>]

Exercises for Numpy and Matplotlib

Exercise 1

Plot the following functions into individual subplots:

$f(x) = e^{-\alpha x^2},\quad g(x) = \alpha x^3-5x^2, \quad h(x) = \mathrm{erf}(x)$

with $\alpha \in \{0.1,0.5,1\}$

hint: use scipy for the definition of $\mathrm{erf}(x)$


In [43]:
%matplotlib inline

Exercise 2

generate two 1D-arrays $A$ and $B$ of size $N$ containing Gaussian random numbers


In [44]:
N = 1e4

Check whether they are correlated using a scatter plot


In [45]:
%matplotlib inline

Plot their 2D density as a contour plot (hint: the density can be obtained from a histogram)


In [ ]:

Plot the density as 3D surface plot


In [46]:
%matplotlib


Using matplotlib backend: MacOSX

In [ ]: