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
Finding your own way (aka RTFM). Hint: there is search box available!
The Matplotlib API docs:
Pyplot, object oriented plotting:
Extensive gallery with examples:
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.
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 [ ]:
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()
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!
In [ ]:
plt.plot(x,x**2)
#Write code to show grid in plot here
plt.grid()
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")
markevery
). See plot options at: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot
In [ ]:
plt.plot(x,x**2, 'o-')
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')
In [ ]:
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])
In [7]:
fig, ax1 = plt.subplots()
ax1.plot(x,x**2)
ax2 = ax1.twinx()
ax2.plot(x,x**3, 'r')
Out[7]:
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]:
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')
We are going to play a bit with regression
In [10]:
x = np.linspace(0, 5*np.pi, 1000)
In [11]:
y = np.sin(x)+(np.random.random(1000)-0.5)
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]:
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]:
In [ ]: