Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
133 views

Python Matplotlib: Gaurav Verma

Matplotlib is a Python library for plotting that provides a MATLAB-like interface through pyplot and pylab. Pyplot provides state-machine style plotting while pylab combines plotting and math functionality. Examples show how to create figures and axes, plot different types of charts, customize labels and titles, and handle multiple subplots. Matplotlib allows both procedural and object-oriented approaches to plotting in Python.

Uploaded by

f,v
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
133 views

Python Matplotlib: Gaurav Verma

Matplotlib is a Python library for plotting that provides a MATLAB-like interface through pyplot and pylab. Pyplot provides state-machine style plotting while pylab combines plotting and math functionality. Examples show how to create figures and axes, plot different types of charts, customize labels and titles, and handle multiple subplots. Matplotlib allows both procedural and object-oriented approaches to plotting in Python.

Uploaded by

f,v
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 21

Python Matplotlib

Gaurav Verma
Plotting - matplotlib

• User friendly, but powerful, plotting capabilites for python


• http://matplotlib.sourceforge.net/

• Once installed (default at Observatory)


>>> import pylab

• Settings can be customised by editing ~/.matplotlib/matplotlibrc


– default font, colours, layout, etc.
• Helpful website
– many examples
Pyplot and pylab

Pylab is a module in matplotlib that gets installed alongside matplotlib;


and matplotlib.pyplot is a module in matplotlib.

• Pyplot provides the state-machine interface to the underlying plotting library


in matplotlib. This means that figures and axes are implicitly and
automatically created to achieve the desired plot. Setting a title will then
automatically set that title to the current axes object.

• Pylab combines the pyplot functionality (for plotting) with the numpy
functionality (for mathematics and for working with arrays) in a single
namespace, For example, one can call the sin and cos functions just like
you could in MATLAB, as well as having all the features of pyplot.

• The pyplot interface is generally preferred for non-interactive plotting (i.e.,


scripting). The pylab interface is convenient for interactive calculations and
plotting, as it minimizes typing.
Matplotlib.pyplot example
Function Description Function Description Function Description
acorr plot the autocorrelation function gca return the current axes gca return the current axes
annotate annotate something in the figure gcf return the current figure gcf return the current figure
arrow add an arrow to the axes gci get the current image, or None gci get the current image, or None
axes create a new axes getp get a graphics property getp get a graphics property
axhline draw a horizontal line across axes grid set whether gridding is on grid set whether gridding is on
axvline draw a vertical line across axes hexbin make a 2D hexagonal binning plot hexbin make a 2D hexagonal binning plot
axhspan draw a horizontal bar across axes hist make a histogram hist make a histogram
axvspan draw a vertical bar across axes hold set the axes hold state hold set the axes hold state
axis set or return the current axis limits ioff turn interaction mode off ioff turn interaction mode off
barbs a (wind) barb plot ion turn interaction mode on ion turn interaction mode on
bar make a bar chart isinteractive return True if interaction mode is on isinteractive return True if interaction mode is on
barh a horizontal bar chart imread load image file into array imread load image file into array
broken_barh a set of horizontal bars with gaps imsave save array as an image file imsave save array as an image file
box set the axes frame on/off state imshow plot image data imshow plot image data
boxplot make a box and whisker plot ishold return the hold state of the current axes
ishold return the hold state of the current axes
cla clear current axes legend make an axes legend legend make an axes legend
clabel label a contour plot adjust parameters used in locating axis adjust parameters used in locating axis
locator_params locator_params
clf clear a figure window ticks ticks
clim adjust the color limits of the current imageloglog a log log plot loglog a log log plot
close close a figure window display a matrix in a new figure preserving display a matrix in a new figure preserving
matshow matshow
colorbar add a colorbar to the current figure aspect aspect
cohere make a plot of coherence margins set margins used in autoscaling margins set margins used in autoscaling
contour make a contour plot pcolor make a pseudocolor plot pcolor make a pseudocolor plot
contourf make a filled contour plot make a pseudocolor plot using a make a pseudocolor plot using a
pcolormesh pcolormesh
csd make a plot of cross spectral density quadrilateral mesh quadrilateral mesh
delaxes delete an axes from the current figure pie make a pie chart pie make a pie chart
draw Force a redraw of the current figure plot make a line plot plot make a line plot
errorbar make an errorbar graph plot_date plot dates plot_date plot dates
make legend on the figure rather than theplotfile plot column data from an ASCII plot column data from an ASCII
figlegend plotfile
axes tab/space/comma delimited file tab/space/comma delimited file
figimage make a figure image pie pie charts pie pie charts
figtext add text in figure coords polar make a polar plot on a PolarAxes polar make a polar plot on a PolarAxes
figure create or change active figure psd make a plot of power spectral densitypsd make a plot of power spectral density
fill make filled polygons quiver make a direction field (arrows) plot quiver make a direction field (arrows) plot
fill_between make filled polygons between two curvesrc control the default params rc control the default params
Matplotlib.pyplot basic example

The easiest way to get started with


plotting using matplotlib is often to
use the MATLAB-like API provided by
matplotlib.

>>> import matplotlib.pyplot as plt


>>> import matplotlib.pylab as plt1
>>> x = plt1.linspace(0, 5, 10)
>>> y = x ** 2
>>> plt.figure(0)
>>> ax= plt.subplot()
>>> ax.plot(x, y, ’r’)
>>> ax.set_xlabel(’x’)
>>> ax.set_ylabel(’y’)
>>> as.set_title(’title’)
>>> plt.show()
Matplotlib.pyplot basic example

Most of the plotting related functions


in MATLAB are covered by the pylab
module. For example, subplot and
color/symbol selection

>>> plt.subplot(1,2,1)
>>> plt.plot(x, y, ’r--’)
>>> plt.subplot(1,2,2)
>>> plt.plot(y, x, ’g*-’);
Matplotlib.pyplot example

Working with multiple figures and


axes. The subplot() command
specifies numrows, numcols, fignum,
where fignum ranges from 1
to numrows*numcols.

import numpy as np
import matplotlib.pyplot as plt

def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)


t2 = np.arange(0.0, 5.0, 0.02)

plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
Matplotlib.pyplot basic example

Matplotlib can be used in object


oriented approach which is
particularly useful when we deal with
subplots

fig = plt.figure()
axes1 = fig.add_axes([0.1, 0.1,
0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.2, 0.5,
0.4, 0.3]) # inset axes
# main figure
axes1.plot(x, y, ’r’)
axes1.set_xlabel(’x’)
axes1.set_ylabel(’y’)
axes1.set_title(’title’)
# insert
axes2.plot(y, x, ’g’)
axes2.set_xlabel(’y’)
axes2.set_ylabel(’x’)
axes2.set_title(’insert title’);
Matplotlib.pyplot basic example

With multiple plots on one screen


sometimes the labels are getting in
the way. Solve this with tight_layout

fig, axes = plt.subplots(nrows=1,


ncols=2)
for ax in axes:
ax.plot(x, y, ’r’)
ax.set_xlabel(’x’)
ax.set_ylabel(’y’)
ax.set_title(’title’)
fig.tight_layout()
Matplotlib.pyplot basic example

Labels and legends and titles


These figure decrations are essential
for presenting your data to others (in
papers and in oral presentations).

>>> ax.set_title("title");
>>> ax.set_xlabel("x")
>>> ax.set_ylabel("y");
>>> ax.legend(["curve1", "curve2", "curve3"]);

>>> ax.plot(x, x**2, label="curve1")


>>> ax.plot(x, x**3, label="curve2")
>>> ax.legend()

>>> fig, ax = plt.subplots()


>>> ax.legend(loc=0) # let matplotlib decide
>>> ax.plot(x, x**2, label="y = x**2")
>>> ax.legend(loc=1) # upper right corner
>>> ax.plot(x, x**3, label="y = x**3")
>>> ax.legend(loc=2) # upper left corner
>>> ax.legend(loc=2); # upper left corner
>>> ax.legend(loc=3) # lower left corner
>>> ax.set_xlabel(’x’)
>>> ax.legend(loc=4) # lower right corner
>>> ax.set_ylabel(’y’)
>>> ax.set_title(’title’);
Matplotlib.pyplot basic example

Changing the font size and family and


using LaTeX formatted tekst.

>>> fig, ax = plt.subplots()


>>> ax.plot(x, x**2, label=r"$y = \alpha^2$")
>>> ax.plot(x, x**3, label=r"$y = \alpha^3$")
>>> ax.legend(loc=2) # upper left corner
>>> ax.set_xlabel(r’$\alpha$’, fontsize=18)
>>> ax.set_ylabel(r’$y$’, fontsize=18)
>>> ax.set_title(’title’);

matplotlib.rcParams.update({’font.size’: 18, ’font.family’: ’serif’})


Matplotlib.pyplot basic example

You have full control over colors,


linewidths and linetypes.
For colors one can use simple syntax
like ‘b’ for blue, ‘g’ for green, etc. or
RGB hex codes with transparency
alpha code:

fig, ax = plt.subplots()
ax.plot(x, x+1, color="red", alpha=0.5) # half-transparant red
ax.plot(x, x+2, color="#1155dd") # RGB hex code for a bluish color
ax.plot(x, x+3, color="#15cc55") # RGB hex code for a greenish color
Matplotlib.pyplot basic example
Line and marker styles are coded:

fig, ax = plt.subplots(figsize=(12,6))
ax.plot(x, x+1, color="blue", linewidth=0.25)
ax.plot(x, x+2, color="blue", linewidth=0.50)
ax.plot(x, x+3, color="blue", linewidth=1.00)
ax.plot(x, x+4, color="blue", linewidth=2.00)
# possible linestype options ‘-‘, ‘{’, ‘-.’, ‘:’, ‘steps’
ax.plot(x, x+5, color="red", lw=2, linestyle=’-’)
ax.plot(x, x+6, color="red", lw=2, ls=’-.’)
ax.plot(x, x+7, color="red", lw=2, ls=’:’)
# custom dash
line, = ax.plot(x, x+8, color="black", lw=1.50)
line.set_dashes([5, 10, 15, 10]) # format: line length, space length, ...
# possible marker symbols: marker = ’+’, ’o’, ’*’, ’s’, ’,’, ’.’, ’1’, ’2’, ’3’, ’4’, ...
ax.plot(x, x+ 9, color="green", lw=2, ls=’*’, marker=’+’)
ax.plot(x, x+10, color="green", lw=2, ls=’*’, marker=’o’)
ax.plot(x, x+11, color="green", lw=2, ls=’*’, marker=’s’)
ax.plot(x, x+12, color="green", lw=2, ls=’*’, marker=’1’)
# marker size and color
ax.plot(x, x+13, color="purple", lw=1, ls=’-’, marker=’o’, markersize=2)
ax.plot(x, x+14, color="purple", lw=1, ls=’-’, marker=’o’, markersize=4)
ax.plot(x, x+15, color="purple", lw=1, ls=’-’, marker=’o’, markersize=8, markerfacecolor="red")
ax.plot(x, x+16, color="purple", lw=1, ls=’-’, marker=’s’, markersize=8,
markerfacecolor="yellow", markeredgewidth=2, markeredgecolor="blue");
Matplotlib.pyplot basic example

Sometimes it is useful to have dual x


or y axes in a figure; for example,
when plotting curves with different
units together. Matplotlib supports this
with the twinx and twiny functions:

>>> fig, ax1 = plt.subplots()


>>> ax1.plot(x, x**2, lw=2, color="blue")
>>> ax1.set_ylabel(r"area $(m^2)$", fontsize=18, color="blue")
>>> for label in ax1.get_yticklabels():
... label.set_color("blue")
...
>>> ax2 = ax1.twinx()
>>> ax2.plot(x, x**3, lw=2, color="red")
>>> ax2.set_ylabel(r"volume $(m^3)$", fontsize=18, color="red")
>>> for label in ax2.get_yticklabels():
... label.set_color("red")
Matplotlib.pyplot basic example

Other 2D plt styles

>>> n = array([0,1,2,3,4,5])
>>> fig, axes = plt.subplots(1, 4, figsize=(12,3))
>>> axes[0].scatter(xx, xx + 0.25*randn(len(xx)))
>>> axes[0].set_title("scatter")
>>> axes[1].step(n, n**2, lw=2)
>>> axes[1].set_title("step")
>>> axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5)
>>> axes[2].set_title("bar")
>>> axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5)
>>> axes[3].set_title("fill_between")
Matplotlib.pyplot basic example

>>> n = np.random.randn(100000)
>>> fig, axes = plt.subplots(1, 2, figsize=(12,4))
>>> axes[0].hist(n)
>>> axes[0].set_title("Default histogram")
Histograms are also a very
useful visualisation tool
>>> axes[0].set_xlim((min(n), max(n)))
>>> axes[1].hist(n, cumulative=True, bins=50)
>>> axes[1].set_title("Cumulative detailed histogram")
>>> axes[1].set_xlim((min(n), max(n)));
Matplotlib.pyplot example
import numpy as np
import matplotlib.pyplot as plt

mu, sigma = 100, 15


x = mu + sigma * np.random.randn(10000)

# the histogram of the data


n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)

plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)

Working with text.


The text() command can be used to
add text in an arbitrary location, and
the xlabel(), ylabel() and title() are
used to add text in the indicated
locations.
Matplotlib.pyplot example

Error bars.
import numpy as np
import matplotlib.pyplot as plt

fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True)


ax = axs[0,0]
ax.errorbar(x, y, yerr=yerr, fmt='o')
ax.set_title('Vert. symmetric')
# With 4 subplots, reduce the number
# of axis ticks to avoid crowding.
ax.locator_params(nbins=4)
ax = axs[0,1]
ax.errorbar(x, y, xerr=xerr, fmt='o')
ax.set_title('Hor. symmetric')
ax = axs[1,0]
ax.errorbar(x, y, yerr=[yerr, 2*yerr], xerr=[xerr, 2*xerr], fmt='--o')
ax.set_title('H, V asymmetric')
ax = axs[1,1]
ax.set_yscale('log')
# Here we have to be careful to keep all y values positive:
ylower = np.maximum(1e-2, y - yerr)
yerr_lower = y - ylower
ax.errorbar(x, y, yerr=[yerr_lower, 2*yerr], xerr=xerr,
fmt='o', ecolor='g')
ax.set_title('Mixed sym., log y')
fig.suptitle('Variable errorbars')
plt.show()
Matplotlib.pyplot example

3D plots.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x =[1,2,3,4,5,6,7,8,9,10]
y =[5,6,2,3,13,4,1,2,4,8]
z =[2,3,3,3,5,7,9,11,9,10]

ax.scatter(x, y, z, c='r', marker='o')

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()
Matplotlib.pyplot example

3D plots.
from numpy import *
import pylab as p
import mpl_toolkits.mplot3d.axes3d as p3

# u and v are parametric variables.


# u is an array from 0 to 2*pi, with 100 elements
u=r_[0:2*pi:100j]
# v is an array from 0 to 2*pi, with 100 elements
v=r_[0:pi:100j]
# x, y, and z are the coordinates of the points for plotting
# each is arranged in a 100x100 array
x=10*outer(cos(u),sin(v))
y=10*outer(sin(u),sin(v))
z=10*outer(ones(size(u)),cos(v)

fig=p.figure()
ax = p3.Axes3D(fig)
ax.plot_wireframe(x,y,z)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
p.show()
Data processing example

End

You might also like