pyplot tutorial
-
matplotlib.pyplotis a collection of command style functions that make matplotlib work like MATLAB -
each
pyplotfunction makes some change to a figure-
create a figure
-
create a plotting area in a figure
-
plot some lines in a plotting area
-
decorate the plot with labels
-
etc…
-
-
matplotlib.pyplotis stateful-
it that it keeps track of the current figure and plotting area
-
and the plotting functions are directed to the current axes
-
code
-
draw line
import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4]) plt.ylabel('some numbers') plt.show()
-
if you provide a single list or array to the
plot()command, matplotlib assumes it is a sequence ofyvalues -
and automatically generates
xvalues for you -
the default
xvector has same length asybut start with0 -
hence the
xdata are[0, 1, 2, 3]
-
-
plot()is a versatile command and will take an arbitrary number of arguments-
to plot
xversusyyou can issue the commandplt.plot([1, 2, 3, 4], [1, 4, 9, 16])
-
-
for every
x,ypair of arguments there is an optional third argument-
which is the format string
-
indicates the color
-
and line type of the plot
-
-
the letters and symbols of the format string are from
MATLAB -
default format string is
b-, which is asolid blue lineimport matplotlib.pyplot as plt plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro') plt.axis([0, 6, 0, 20]) plt.show()

-
the
axis()command in the example above takes a list of[xmin, xmax, ymin, ymax] -
and specifies the viewport of the axes
-
-
all sequences are converted to numpy arrays internally
import numpy as np import matplotlib.pyplot as plt # evenly sampled time at 200ms intervals t = np.arange(0., 5., 0.2) # red dashes, blue squares and green triangles plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') plt.show()
controlling line properties
-
line have many attributes that you can set
-
linewidth
-
dash style
-
antialiased
-
-
there are several ways to set line properties
-
use keyword args
plt.plot(x, y, linewidth=2.0) -
use the setter methods of the
Line2Dinstance.plotreturns a list of linesline1, line2 = plot(x1, y1, x2, y2) line, = plt.plot(x, y, '-') # turn off antialising line.set_antialiased(False) -
use the
setp()commandlines = plt.plot(x1, y1, x2, y2) # use keyword args plt.setp(lines, color='r', linewidth=2.0) # or MATLAB style string values pairs plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
-
Line2D properties
| Property | Value Type |
|---|---|
| alpha | float |
| animated | [True | False] |
| antialiased or aa | [True | False] |
| clip_box | a matplotlib.transform.Bbox instance |
| clip_on | [True | False] |
| clip_path | a Path instance and a Transform instance, a Patch |
| color or c | any matplotlib color |
| contains | the hit testing function |
| dash_capstyle | ['butt' | 'round' | 'projecting'] |
| dash_joinstyle | ['miter' | 'round' | 'bevel'] |
| dashes | sequence of on/off ink in points |
| data | (np.array xdata, np.array ydata) |
| figure | a matplotlib.figure.Figure instance |
| label | any string |
| linestyle or ls | [ '-' | '--' | '-.' | ':' | 'steps' | ...] |
| linewidth or lw | float value in points |
| lod | [True | False] |
| marker | [ '+' | ',' | '.' | '1' | '2' | '3' | '4' ] |
| markeredgecolor or mec | any matplotlib color |
| markeredgewidth or mew | float value in points |
| markerfacecolor or mfc | any matplotlib color |
| markersize or ms | float |
| markevery | [ None | integer | (startind, stride) ] |
| picker | used in interactive line selection |
| pickradius | the line pick selection radius |
| solid_capstyle | ['butt' | 'round' | 'projecting'] |
| solid_joinstyle | ['miter' | 'round' | 'bevel'] |
| transform | a matplotlib.transforms.Transform instance |
| visible | [True | False] |
| xdata | np.array |
| ydata | np.array |
| zorder | any number |
working with multiple figures and axes
-
MATLAB and
pyplothave the concept of the current figure and the current axes -
all plotting commands apply to the current axes
-
the function
gca()returns the current axes (amatplotlib.axes.Axesinstance) -
and
gcf()returns the current figure (matplotlib.figure.Figureinstance)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) t1 = 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--') plt.show()
-
you can create multiple figures by using multiple
figure()calls with an increasing figure numberimport matplotlib.pyplot as plt plt.figure(1) # the first figure plt.subplot(211) # the first subplot in the first figure plt.plot([1, 2, 3]) plt.subplot(212) # the second subplot in the first figure plt.plot([4, 5, 6]) plt.figure(2) # the second figure plt.plot([4, 5, 6]) # creates a subplot(111) by default plt.figure(1) # figure 1 current; subplot(212) still current plt.subplot(211) # make subplot(211) in figure 1 current plt.title('easy as 1, 2, 3') # subplot 211 title -
you can clear the current figure with
clf()and the current axes withcla() -
a figure is not completely released until the figure is explicitly closed with
close()
working with text
-
the
text()command can be used to add text in an arbitrary location -
the
xlabel(), ylabel()andtitle()are used to add text in the indicated locationsimport 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) plt.show()
-
all the
text()commands return anmatplotlib.text.Textinstancet = plt.xlabel('my data', fontsize=14, color='red')- you can customize the properties by passing keyword arguments into the text functions or using
setp()
- you can customize the properties by passing keyword arguments into the text functions or using
annotating text
-
annotate()method provides helper functionality to make annotation ease -
there 2 points to consider
-
the location being annotated represented by the argument
xy -
the location of the text
xytextimport numpy as np import matplotlib.pyplot as plt ax = plt.subplot(111) t = np.arange(0.0, 5.0, 0.01) s = np.cos(2*np.pi*t) line, = plt.plot(t, s, lw=2) plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05), ) plt.ylim(-2,2) plt.show()

-
see annotating text and annotating axes
-
more examples can be found in pylab-examples-annotation-demo
-