990 lines (810 with data), 37.3 kB
plot_table_border = 'border=1 cellspacing=1 cellpadding=1'
font_props = (
('alpha', 'The alpha transparency on 0-1 scale'),
('color', 'a matplotlib <a href=pylab#-colors>color</a> argument'),
('fontangle', 'italic | normal | oblique'),
('fontname', 'Sans | Helvetica | Courier | Times | Others'),
('fontsize', 'an scalar, eg, 10'),
('fontweight', 'normal | bold | light 4'),
('horizontalalignment', 'left | center | right'),
('rotation', 'horizontal | vertical'),
('verticalalignment', 'bottom | center | top'),
)
line_props = (
('alpha', 'The alpha transparency on 0-1 scale'),
('antialiased', 'True | False - use antialised rendering'),
('color', 'a matplotlib <a href=matplotlib.pyplot.html#-colors>color</a> arg'),
('label', 'a string optionally used for legend'),
('linestyle', "One of -- : -. -"),
('linewidth', 'a float, the line width in points'),
('marker', "One of + , o . s v x > < ^"),
('markeredgewidth', 'The line width around the marker symbol'),
('markeredgecolor', 'The edge color if a marker is used'),
('markerfacecolor', 'The face color if a marker is used'),
('markersize', 'The size of the marker in points'),
)
@header@
<h2>Using matplotlib</h2>
If you are new to python, I recommend reading the <a
href=http://docs.python.org/tut/tut.html>python
tutorial</a> and <a
href=http://scipy.org/Documentation>numpy tutorial</a> before working with matplotlib.
Otherwise you may get frustrated. When you feel comfortable with
both, you'll find matplotlib easy.<p>
There are a lot of features under the hood in matplotlib. This
tutorial just scratches the surface. When you are finished with it,
the next step (other than getting to work on your own figures, of
course) is to download the source distribution (*.tar.gz or *.zip) and
take a look at the
<a href=http://matplotlib.sf.net/examples>matplotlib examples</a>
subdirectory. If you are working with date plots you'll find several
date demos in the ``pylab`` subdirectory and with obvious filenames
like <a href=examples/pylab_examples/date_demo1.py>date_demo1.py</a>.
Likewise, you'll find examples for images
<a href=examples/pylab_examples/image_demo.py>image_demo.py</a>, contouring
<a href=examples/pylab_examples/contour_demo.py>contour_demo.py</a>. If you
are using matplotlib with a graphical user interface, you can find
examples in the ``user_interfaces`` subdirectory, eg
<a href=examples/user_interfaces/embedding_in_wx.py>embedding_in_wx.py</a>
and many more. Likewise, there are example directories for matplotlib
event handling ``event_handling``, the api ``api``, and so on.
Because these are not included with the standard windows installer,
they are often overlooked, which is why I emphasize them here.<p>
The next place to turn to find the hidden gems is the <a
href=whats_new.html>what's new</a> page. Every feature ever
introduced into matplotlib is listed on that page with the version it
was introduced, usually with links to examples and functions.
Scrolling through that page is one of the best ways to find out what
capabilities and customizations are supported.<p>
matplotlib is designed to work in a variety of settings: some people
use it in "batch mode" on a web server to create images they never
look at. Others use graphical user interfaces (GUIs) to interact with
their plots. Thus you must customize matplotlib to work like you want
it too. In particular, you need to take a look at the customization
file <a href=matplotlibrc>matplotlibrc<a/>, in which you can set
whether you want to just create images or use a GUI (the
<tt>backend</tt> setting), and whether you want to work interactively
from the shell (the <tt>interactive</tt> setting). Also, please read
<a href=interactive.html>interactive use</a>, <a
href=faq.html#SHOW>What's up with show?</a>, and <a
href=faq.html#FREEZE>My matplotlib window is freezing</a> before
trying type in the examples below, to avoid the confusions that bite
many new matplotlib users. Or at least make a mental note to come
back and read them if you encounter any problems.<p>
Using matplotlib should come naturally if you have ever plotted with
matlab, and should be fairly straightforward if you haven't. The
basic entity is a figure, which contains axes, which contain plots.
The axes are decorated with xlabels, ylabels, titles, ticklabels, and
text.<p>
Here is about the simplest script you can use to create a figure with
matplotlib<p>
<table @plot_table_border@><tr><td>
<table>
<caption><h4>A simple plot</h4></caption>
<tr><td valign=top><img src=tut/firstfig.png></td></tr>
<tr><td valign=top halign=left>
<pre>
from pylab import *
plot([1,2,3,4])
show()
</pre>
</td></tr>
</table>
</td></tr>
</table><br>
If you are new to python, the first question you are probably asking
yourself about this plot is, "Why does the xaxis range from 0-3 and
the yaxis from 1-4." The answer is that if you provide a single list
or array to the plot command, matplotlib assumes it a vector of
y-values, and automatically generates the x-values for you. Since
python ranges start with 0, the default x vector has the same length
as your y vector but starts with 0. Hence the x vector is [0,1,2,3].
Of course, if you don't want the default behavior, you can supply the
x data explicitly, as in <tt>plot(x,y)</tt> where <tt>x</tt> and
<tt>y</tt> are equal length vectors.<p> <a
href=matplotlib.pyplot.html#-plot>plot</a> is a versatile command, and will take
an arbitrary number of arguments. For example, to plot x versus y,
you can issue the command<p>
<pre>
plot([1,2,3,4], [1,4,9,16])
</pre>
For every x, y pair of arguments, there is a optional third argument
which is the format string that indicates the color and line type of
the plot. The letters and symbols of the format string are from
matlab, and you concatenate a color string with a line style string.
The default format string is 'b-', which is a solid blue line (don't
ask me, talk to <a href=http://www.mathworks.com/products/matlab>The
Mathworks</a>). For example, to plot the above with red circles, you
would issue<p>
<table @plot_table_border@><tr><td>
<table>
<caption><h4>Using format strings</h4></caption>
<tr><td valign=top><img src=tut/secondfig.png></td></tr>
<tr><td valign=top halign=left>
<pre>
from pylab import *
plot([1,2,3,4], [1,4,9,16], 'ro')
axis([0, 6, 0, 20])
savefig('secondfig.png')
show()
</pre>
</td></tr>
</table>
</td></tr></table><br>
See the <a href=matplotlib.pyplot.html#-plot>plot</a> documentation for a
complete list of line styles and format strings. The <a
href=matplotlib.pyplot.html#-axis>axis</a> command in the example above takes a
list of <tt>[xmin, xmax, ymin, ymax]</tt> and specifies the view port
of the axes.<p>
If matplotlib were limited to working with lists, it would be fairly
useless for numeric processing. Generally, you will use
<a href=http://numpy.scipy.org/>numpy</a> arrays. In fact, all
sequences are converted to numpy arrays internally. The example
below illustrates a plotting several lines with different format
styles in one command using arrays.<p>
<table @plot_table_border@><tr><td>
<table>
<caption><h4>Multiple lines with one plot command</h4></caption>
<tr><td valign=top><img src=tut/thirdfig.png></td></tr>
<tr><td valign=top halign=left>
<pre>
from pylab import *
t = arange(0.0, 5.2, 0.2)
# red dashes, blue squares and green triangles
plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
show()
</pre>
</td></tr>
</table>
</td></tr></table><br>
<h3><a name=lineprops>Controlling line properties</a></h3>
Lines have many attributes that you can set: linewidth, dash style,
antialiased, etc; see <a
href=matplotlib.lines.html>lines</a>.<p>
There are several ways to set line properties
<pre>
# Use keyword args
plot(x, y, linewidth=2.0)
# Use the setter methods of the Line2D instance. plot returns a list
# of lines; eg line1, line2 = plot(x1,y1,x2,x2). Below I have only
# one line so it is a list of length 1. I use tuple unpacking in the
# line, = plot(x, y, 'o') to get the first element of the list
line, = plot(x, y, 'o')
line.set_antialiased(False) # turn off antialising
# Use the set command. The example below uses matlab handle graphics
# style command to set multiple properties on a list of lines. Set
# works transparently with a list of objects or a single object
lines = plot(x1, y1, x2, y2)
setp(lines, color='r', linewidth=2.0)
# set also accepts matlab style pairs of arguments with property names
# as strings, though I prefer the pythonic keyword arguments above
setp(lines, 'color', 'r', 'linewidth', 2.0)
</pre>
<h4>Line Properties</h4>
<table @default_table@>
<tr><th >Property</th> <th>Values</th></tr>
+ for prop,values in line_props:
<tr><td align=left>@prop@</td> <td align=left>@values@</td></tr>
-
</table><br>
To get a list of settable line properties, call the <a
href=matplotlib.pyplot.html#-setp>setp</a> function with a line or lines
as argument
<pre>
>>> lines = plot([1,2,3])
>>> setp(lines)
</pre>
<a name=figs_and_axes>
<h3>Working with multiple figure and axes</h3>
</a>
Matlab, and pylab, have the concept of the current figure
and the current axes. All plot and text label commands apply to the
current axes. The function <a
href=matplotlib.pyplot.html#-gca>gca</a> returns the current axes as
an <a href=matplotlib.axes.html#Axes>Axes</a> instance, and <a
href=matplotlib.pyplot.html#-gcf>gcf</a> returns the current figure as
a <a href=matplotlib.figure.html#Figure>Figure</a>
instance.<p>
Normally, you don't have to worry about this, because it is all taken
care of behind the scenes. Here is an script to create two subplots<p>
<table @plot_table_border@><tr><td>
<table>
<caption><h4>Multiple subplots</h4></caption>
<tr><td valign=top><img src=tut/subplot.png></td></tr>
<tr><td valign=top halign=left>
<pre>
from pylab import *
def f(t):
s1 = cos(2*pi*t)
e1 = exp(-t)
return multiply(s1,e1)
t1 = arange(0.0, 5.0, 0.1)
t2 = arange(0.0, 5.0, 0.02)
figure(1)
subplot(211)
plot(t1, f(t1), 'bo', t2, f(t2), 'k')
subplot(212)
plot(t2, cos(2*pi*t2), 'r--')
show()
</pre>
</td></tr>
</table>
</td></tr></table><br>
The <a href=matplotlib.pyplot.html#-figure>figure</a> command here is optional
because 'figure(1)' will be created by default, just as a
<tt>subplot(111)</tt> will be created by default if you don't manually
specify an axes. The <a href=matplotlib.pyplot.html#-subplot>subplot</a> command
specifies <tt>numrows, numcols, fignum</tt> where <tt>fignum</tt>
ranges from 1 to <tt>numrows*numcols</tt>. The commas in the subplot
command are optional if <tt>numrows*numcols<10</tt>. So
<tt>subplot(211)</tt> is identical to <tt>subplot(2,1,1)</tt>. You can
create an arbitrary number of subplots and axes. If you want to place
an axes manually, ie, not on a rectangular grid, use the <a
href=matplotlib.pyplot.html#-axes>axes</a> command, which allows you to specify
the location as <tt>axes([left, bottom, width, height])</tt> where all
values are in fractional (0 to 1) coordinates. See <a
href=examples/pylab_examples/axes_demo.py>axes_demo.py</a> for an example of placing
axes manually and <a href=examples/pylab_examples/line_styles.py>line_styles.py</a> for an example with
lots-o-subplots.<p>
You can create multiple figures by using multiple <a
href=matplotlib.pyplot.html#-figure>figure</a> calls with an
increasing figure number. Of course, each figure can contain as many
axes and subplots as your heart desires.<p>
<pre>
from pylab import *
figure(1) # the first figure
plot([1,2,3])
figure(2) # a second figure
plot([4,5,6])
figure(1) # figure 1 current
title('Easy as 1,2,3') # figure 1 title
show()
</pre>
You can clear the current figure with <a
href=matplotlib.pyplot.html#-clf>clf</a> and the current axes with
<a
href=matplotlib.pyplot.html#-cla>cla</a>
<a name="text">
<h3>Working with text</h3>
</a>
All of the text commands (<a
href=matplotlib.pyplot.html#-xlabel>xlabel</a>, <a
href=matplotlib.pyplot.html#-ylabel>ylabel</a>, <a
href=matplotlib.pyplot.html#-title>title</a>, and <a
href=matplotlib.pyplot.html#-text>text</a>) take optional keyword arguments or
dictionaries to specify the font properties. There are three ways to
specify font properties in matplotlib: handle graphics calls using <a
href=matplotlib.pyplot.html#-setp>setp</a>, object oriented methods, and font
dictionaries.<p>
The text commands return an <a href=matplotlib.text.html>Text</a>
instance (or a list of instances if multiple text objects are
created), and the following font properties can be set; these names
are compatible with matlab handle graphics for text<p>
<table @default_table@>
<tr><th >Property</th> <th>Values</th></tr>
+ for prop,values in font_props:
<tr><td align=left>@prop@</td> <td align=left>@values@</td></tr>
-
</table><br>
See <a href=screenshots.html#align_text>align_text</a> for
examples of how to control the alignment and orientation of text.<p>
Here is an example adding text to a simple plot<p>
<table @plot_table_border@><tr><td>
<table>
<caption><h4>Simple text handling</h4></caption>
<tr><td valign=top><img src=tut/text_simple.png></td></tr>
<tr><td valign=top halign=left>
<pre>
from pylab import *
plot([1,2,3])
xlabel('time')
ylabel('volts')
title('A line')
show()
</pre>
</td></tr>
</table>
</td></tr>
</table><br>
<h4><a name=handle>Controlling text properties with handle graphics</a></h4>
If you want to change a text property, and you like to use matlab
handle graphics, you can use the <a
href=matplotlib.pyplot.html#-setp>setp</a> command to set any of the
properties listed in the table above. For example, to make a red bold
<a href=matplotlib.pyplot.html#-xlabel>xlabel</a>, you would use<p>
<pre>
t = xlabel('time')
setp(t, color='r', fontweight='bold')
</pre>
Set also works with a list of text instances. The following changes
the properties of all the tick labels.
<pre>
labels = getp(gca(), 'xticklabels')
setp(labels, color='r', fontweight='bold')
</pre>
<h4><a name=oo>Controlling text using object methods</a></h4>
The <a href=matplotlib.pyplot.html#-setp>setp</a> command is just a
wrapper around the <a href=matplotlib.text.html>Text</a> set methods.
If you prefer using instance methods, you just prepend <tt>set_</tt>
to the text property and make a normal python instance method call, as
in<p>
<pre>
t = xlabel('time')
t.set_color('r')
t.set_fontweight('bold')
</pre>
<h4>Controlling text using kwargs and dicts</h4>
All of the text commands take an optional dictionary and keyword
arguments to control font properties. For example, if you want to set
a default font theme, and override individual properties for given
text commands, you could do something like<p>
<table @plot_table_border@><tr><td>
<table>
<caption><h4>Controlling fonts using dictionaries</h4></caption>
<tr><td valign=top><img src=tut/text_dict.png></td></tr>
<tr><td valign=top halign=left>
<pre>
from pylab import *
font = {'fontname' : 'Courier',
'color' : 'r',
'fontweight' : 'bold',
'fontsize' : 11}
plot([1,2,3])
title('A title', font, fontsize=12)
text(0.5, 2.5, 'a line', font, color='k')
xlabel('time (s)', font)
ylabel('voltage (mV)', font)
show()
</pre>
</td></tr>
</table>
</td></tr></table><br>
Now, all of the text has the default theme, which is set by the
dictionary <tt>font</tt> (bold, Courier, red, 11 point), but
individual pieces of text can selectively override properties by
passing keyword arguments. For example the <a
href=matplotlib.pyplot.html#-text>text</a> command uses color black
with the color string 'k'.<p>
<h4><a name=mathtext>Writing mathematical expressions</aa></h4>
You can use TeX markup in your expressions; see the <a
href=matplotlib.mathtext.html>mathtext</a> documentation for usage,
requirements and backend information.<p>
Any text element can use math text. You need to use raw strings
(preceed the quotes with an <tt>'r'</tt>), and surround the string
text with dollar signs, as in TeX. Regular text and mathtext can be
interleaved within the same string.<p>
Mathtext can use the Bakoma Computer Modern fonts, STIX fonts or a
Unicode font that you provide. The mathtext font can be selected with
the customization variable "mathtext.fontset".<p>
<pre>
# plain text
title('alpha > beta')
# math text
title(r'$\alpha > \beta$')
</pre>
To make subscripts and superscripts use the '_' and '^' symbols, as in
<pre>
title(r'$\alpha_i > \beta_i$')
</pre>
You can also use a large number of the TeX symbols, as in <tt>\infty,
\leftarrow, \sum, \int</tt>; see <a
href=matplotlib.mathtext.html>mathtext</a> for a complete list. The
over/under subscript/superscript style is also supported. To write
the sum of x_i from 0 to infinity, you could do <p>
<pre>
text(1, -0.6, r'$\sum_{i=0}^\infty x_i$')
</pre>
The default font is <i>italics</i> for mathematical symbols. To
change fonts, eg, to write "sin" in a Roman font, enclose the text in
a font command, as in
<pre>
text(1,2, r's(t) = $\mathcal{A}\mathrm{sin}(2 \omega t)$')
</pre>
Even better, many commonly used function names that are typeset in a
Roman font have shortcuts. So the expression above could be written
as follows:
<pre>
text(1,2, r's(t) = $\mathcal{A}\sin(2 \omega t)$')
</pre>
Here "s" and "t" are variable in italics font (default), "sin" is in
Roman font, and the amplitude "A" is in caligraphy font. The font
choices are Roman <tt>\mathrm</tt>, italics <tt>\mathit</tt>, caligraphy
<tt>\mathcal</tt>, and typewriter <tt>\mathtt</tt>. If using the STIX
fonts, you also have the choice
of blackboard (double-struck) <tt>\mathbb</tt>,
circled <tt>\mathcircled</tt>, Fraktur <tt>\mathfrak</tt>, script
(cursive) <tt>\mathscr</tt> and sans-serif <tt>\mathsf</tt>.<p>
The following accents are provided: <tt>\hat</tt>, <tt>\breve</tt>,
<tt>\grave</tt>, <tt>\bar</tt>, <tt>\acute</tt>, <tt>\tilde</tt>,
<tt>\vec</tt>, <tt>\dot</tt>, <tt>\ddot</tt>. All of them have the
same syntax, eg to make an overbar you do <tt>\bar{o}</tt> or to make an o
umlaut you do <tt>\ddot{o}</tt>.<p>
<table @plot_table_border@><tr><td>
<table>
<caption><h4>Using math text</h4></caption>
<tr><td valign=top><img src=tut/mathtext_tut.png></td></tr>
<tr><td valign=top halign=left>
<pre>
from pylab import *
t = arange(0.0, 2.0, 0.01)
s = sin(2*pi*t)
plot(t,s)
title(r'$\alpha_i > \beta_i$', fontsize=20)
text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$',
fontsize=20)
xlabel('time (s)')
ylabel('volts (mV)')
savefig('mathtext_tut', dpi=50)
show()
</pre>
</td></tr>
</table>
</td></tr></table><br>
<a name="navigation">
<h3>Interactive navigation</h3>
</a>
All figure windows come with a navigation toolbar, which can be used
to navigate through the data set. You can select either the "classic"
or newfangled toolbar "toolbar2" in your <a
href=matplotlibrc>matplotlibrc</a> file using the <tt>toolbar</tt>
setting.
If you want to interact with very large data sets, matplotlib supports
data clipping where the data is clipped with numerix before they are
plotted to the active viewport, so you can have a very large data set,
plot the whole thing, set the view limits to a narrow range, and
interactively scroll through the data with good interactive refersh
rates. I wrote an EEG viewer (see the screenshot) in matplotlib and
routinely plot 25 MB data sets in matplotlib with good performance on
a 800 MHz PC. See the <a
href=examples/pylab_examples/stock_demo.py>stock_demo.py</a> that comes with the
matplotlib src for an example of a longish data set with a limited
data view -- only the first 3 of 60 days worth of minute by minute
stock quotes for Intel and Apple are initially shown in the view port.
As in this example, data clipping is a feature that must be explicitly
turned on.<p>
<a name=classic><h4>Classic toolbar</h4></a>
You can pan and zoom on the X and Y axis for any combination of the
axes that are plotted. If you have a wheel mouse, you can move
bidirectionally by scrolling the wheel over the controls. For
examples, the wheel mouse can be used to pan left or right by
scrolling over <i>either</i> of the left arrow or right arrow buttons,
so you never have to move the mouse to pan the x-axis left and right.
If you don't have a wheel mouse, buy one!<p>
<table>
<tr><td><img src=tut/navcontrols.png></td></tr> <tr><td
width=400> <i>The left widget that says 'All' on the controls on the
bottom of the figure is a drop down menu used to select which axes the
controls affect. You can select all, none, single, or combinations of
axes. The first set of 4 controls are used to pan left, pan right,
zoom in and zoom out on the x axes. The second set are used to pan
up, pan down, zoom in and zoom out on the y axes. The remaining
buttons are used to redraw the figure, save (PNG or JPEG) the figure,
or to close the figure window.</i> </td></tr> </table><br>
<a name=toolbar2><h4>toolbar2</h4></a>
The toolbar2 buttons behave very differently from the classic the
classic matplotlib toolbar (else why introduce a new one!) despite the
visual similarity of the forward and back buttons. See below for
details.<p>
<table>
<b>The <tt>Forward</tt> and <tt>Back</tt></b> buttons are akin to the web
browser forward and back buttons. They are used to navigate back and
forth between previously defined views. They have no meaning unless
you have already navigated somewhere else using the pan and zoom
buttons. This is analogous to trying to click <tt>Back</tt> on your
web browser before visiting a new page --nothing happens.
<tt>Home</tt> always takes you to the first, default view of your
data. For <tt>Home</tt>, <tt>>Forward</tt> and <tt>Back</TT>, think
web browser where data views are web pages. Use the pan and zoom to
rectangle to define new views.<p>
<b>The Pan/Zoom</b> button has two modes: pan and zoom. Click this toolbar
button to activate this mode. Then put your mouse somewhere over an
axes.
<ul>
<li>Pan Mode: Press the left mouse button and hold it, dragging it to
a new position. When you release it, the data under the point where
you pressed will be moved to the point where you released. If you
press 'x' or 'y' while panning, the motion will be contrained to the
x or y axis, respectively</li>
<li>Zoom Mode: Press the right mouse button, dragging it to a new
position. The x axis will be zoomed in proportionate to the
rightward movement and zoomed out proportionate to the leftward
movement. Ditto for the yaxis and up/down motions. The point under
your mouse when you begin the zoom remains stationary, allowing you
to zoom to an arbitrary point in the figure. You can use the
modifier keys 'x', 'y' or 'CONTROL' to constrain the zoom to the x
axes, the y axes, or aspect ratio preserve, respectively. </li>
</ul>
<b>The Zoom to rectangle button</b>: Click this toolbar button to activate
this mode. Put your mouse somewhere over and axes and press the left
mouse button. Drag the mouse while holding the button to a new
location and release. The axes view limits will be zoomed to the
rectangle you have defined. There is also an experimental 'zoom out
to rectangle' in this mode with the right button, which will place
your entire axes in the region defined by the zoom out rectangle.<p>
<b>Subplot configuration</b> Use this tool to configure the parameters
of the subplot: the left, right, top, bottom, space between the rows
and space between the columns.<p>
<b>Save</b>: click this button to launch a file save dialog. All the *Agg
backends know how to save the following image types: PNG, PS, EPS,
SVG. There is no support currently in Agg for writing to JPEG, TIFF
(the regular wx and gtk backends handle these types). It is possible
to use matplotlib/agg + PIL to convert agg images to one of these
other formats if required. I can provide a recipe for you. I prefer
PNG over JPG and TIFF, which is why I haven't worked too hard to
include these other image formats in agg.<p>
<table>
<tr><td><img src=tut/navcontrols2.png></td></tr> <tr><td
width=400> <i>The new toolbar2</i> </td></tr> </table><br>
<a name="rc">
<h3>Customizing matplotlib</h3>
</a>
matplotlib uses an rc configuration file <a
href=matplotlibrc>matplotlibrc</a>. At installation time, this is
placed in a standard distutils path, eg
<tt>C:\Python23\share\matplotlib\matplotlibrc</tt> on windows or
<tt>/usr/local/share/matplotlib/matplotlibrc</tt> on linux and
friends. Every time you install matplotlib, this file will be
overwritten, so if you want your customizations to be saved, please
move this file to your HOME directory and make sure the HOME
environment variable is set.<p>
You can control the defaults of almost every property in matplotlib:
figure size and dpi, line width, color and style, axes, axis and grid
properties, text and font properties and so on. The format of the
file is documented within it, so please see <a
href=matplotlibrc>matplotlibrc</a> for more information.<p>
You can also dynamically change the defaults in a python script or
interactively from the python shell using the <a
href=matplotlib.pyplot.html#-rc>rc</a> command. For example to change
the default line properties, you could do
<pre>
>>> rc('lines', linewidth=2, color='r')
</pre>
And the default lines would be thicker and red. All rc parameters
except <tt>backend, numerix, interactive, toolbar, timezone and
datapath</tt> can be customized this way dyanmically. See <a
href=matplotlib.pyplot.html#-rc>rc</a> for more information.
<a name="axes_prop">
<h3>Controlling axes properties</h3>
</a>
The <a href=matplotlib.pyplot.html#-axes>axes</a> and <a
href=matplotlib.pyplot.html#-subplot>subplot</a> commands return the
Axes instance that is created, and you can use that to control
properties of the axis, such as ticklines, ticklabels, gridlines, etc,
using the set method calls from the <a href=axis.html#Axis>Axis</a>
API. Or if you prefer matlab handle graphics commands, you can use
the <a href=matplotlib.pyplot.html#-setp>setp</a> to control axis
properties.<p>
<pre>
subplot(111)
plot([1,2,3])
glines = getp(gca(), 'gridlines')
# make the gridlines blue and thicker
setp(glines, 'color', 'b', 'linewidth', 2)
# get the patches.Rectangle instance increase
# the linewidth of the rectangular axis frame
frame = gca(gca(), 'frame')
setp(frame, 'linewidth', 2)
</pre>
One thing that comes up a lot in my plots when I have multiple
subplots is that I often want to turn off the xticklabels on all
except the lowest subplot, if the scaling is the same. Here's how to
do it with handle graphics; recall that <a
href=matplotlib.pyplot.html#-gca>gca</a> returns a handle to the
current axis<p>
<pre>
subplot(211)
plot([1,2,3], [1,2,3])
setp(gca(), xticklabels=[])
subplot(212)
plot([1,2,3], [1,4,9])
</pre>
and the same with instance methods
<pre>
a1 = subplot(211)
plot([1,2,3], [1,2,3])
a1.set_xticklabels([])
subplot(212)
plot([1,2,3], [1,4,9])
</pre>
<a name="interactive">
<h3>Using the interactive shell</h3>
</a>
You can work with matplotlib interactively from the python shell. The
recommended python shell is <a
href=http://ipython.scipy.org>ipython</a>, which includes explcit
support for all of the matplotlib backends and much more, with the
<tt>pylab</tt> option.</p>
For other interactive environments, there are known incompatiblities
with some of the backends and some of the IDEs, because they use
different GUI event handlers. If you want to use matplotlib from an
IDE, please consult the backends documentation for compatibility
information. With the standard, unmodified python shell, you must use
the TkAgg backend. To work interactively with other backends, shells
or IDEs, please consult <a href=backends.html>backends</a> and <a
href=interactive.html>interactive</a>.
<a name="events">
<h3>Event handling</h3>
</a>
When visualizing data, it's often helpful to get some interactive
input from the user. All graphical user interfaces (GUIs) provide
event handling to determine things like key presses, mouse position,
and button clicks. matplotlib supports a number of GUIs, and provides
an interface to the GUI event handling via the <a
href=matplotlib.pyplot.html#-connect>connect</a> and <a
href=matplotlib.pyplot.html#-disconnect>disconnect</a> methods
of the pylab interface. API users will probably want to use their
GUIs event handling directly, but do have the option of using their
<tt>FigureCanvas.mpl_connect</tt> method.<p>
matplotlib uses a callback event handling mechanism. The basic idea
is that you register an event that you want to listen for, and the
figure canvas will call a user defined function when that event
occurs. For example, if you want to know where the user clicks a
mouse on your figure, you could define a function
<pre>
def click(event):
print 'you clicked', event.x, event.y
#register this function with the event handler
connect('button_press_event', click)
</pre>
Then whenever the user clicks anywhere on the figure canvas, your
function will be called and passed a <a
href=matplotlib.backend_bases.html#MplEvent>MplEvent</a> instance.
The event instance will have the following attributes defined.
<table @default_table@>
<tr><td><b>Property</b></td><td><b>Meaning</b></td></tr>
<tr><td>x</td><td>x position - pixels from left of canvas</td></tr>
<tr><td>y</td><td>y position - pixels from bottom of canvas</td></tr>
<tr><td>button</td><td>button pressed None, 1, 2, 3</td></tr>
<tr><td>inaxes</td><td>the Axes instance if mouse is over axes (or None)</td></tr>
<tr><td>xdata</td><td>x coord of mouse in data coords (None if mouse
isn't over axes)</td></tr>
<tr><td>ydata</td><td>y coord of mouse in data coords (None if mouse
isn't over axes)</td></tr>
<tr><td>name</td><td>The string name of the event</td></tr>
<tr><td>canvas</td><td>The FigureCanvas instance the event occured in</td></tr>
<tr><td>key</td><td>The key press if any, eg 'a', 'b', '1'. Also
records 'control and 'shift'</td></tr>
</table>
You can connect to the following events: 'button_press_event',
'button_release_event', 'motion_notify_event'.
Here's an example to get the mouse location in data coordinates as the
mouse moves
<pre>
from pylab import *
plot(arange(10))
def on_move(event):
# get the x and y pixel coords
x, y = event.x, event.y
if event.inaxes:
print 'data coords', event.xdata, event.ydata
connect('motion_notify_event', on_move)
show()
</pre>
<h3><a name="dates">Plotting dates</a></h3>
matplotlib handles date plotting by providing converter functions to
convert python datetime objects to and from floating point numbers.
These numbers represent days in the Proleptic Greogrian Calendar UTC
time. The advantage of using UTC is that there is no daylight savings
time or timezone offset, which facilitates time calculation. However,
this is just the internal format matplotlib uses, and timezone support
is provided. The supported date range is the same as the python
datetime module: years 0001-9999<p>
<b>Note that before matplotlib 0.63, dates were represented as seconds
since the epoch (1972) and did not have timezone support. The code
was rewritten to use datetime objects both to extend the time range
over which date plots work and to support time zones. Thus
dateplotting requires python2.3. Please read this section
carefully and consult <a href=API_CHANGES>API_CHANGES<a/> to see what
changes are required to migrate old code. Also note that many of the
date locator functions which have the same name now have a different
(and more general) constructor syntax.</b><p>
There are three datetime conversion functions: <a
href=matplotlib.dates.html#-date2num>date2num</a>, <a
href=matplotlib.dates.html#-num2date>num2date</a> and <a
href=matplotlib.dates.html#-drange>drange</a>. date2num takes a
python datetime (or sequence of datetimes) and returns a float or
sequence of floats. num2date does the inverse. drange takes a start
date, end date and datetime timedelta object and returns a sequence of
floats.<p>
<pre>
date1 = datetime.date( 1952, 1, 1 )
date2 = datetime.date( 2004, 4, 12 )
delta = datetime.timedelta(days=100)
dates = drange(date1, date2, delta)
</pre>
The function <a href=matplotlib.pyplot.html#-plot_date>plot_date</a>
is used to plot a series of y-values against floating point dates.
Since the x axis is just a sequence of floats, you could just as
easily use <a href=matplotlib.pyplot.html#-plot>plot</a>. In fact,
this is just what plot_date does under the hood. The only difference
is that plot_date picks a date tick locator and a date tick formatter,
and tries to make an intelligent default choice based on the range of
dates presented. If you want to use custom date tickers and
formatters, you can just as easily use the plot command for date
plots.<p>
<pre>
# make up some random y values
s = rand(len(dates))
plot_date(dates, s)
</pre>
<h4>date ticking with dateutils</h4> Another new change in date
plotting with matplotlib-0.63 is that the powerful <a
href=https://moin.conectiva.com.br/DateUtil>dateutil</a> package is
included to support date tick locating. dateutil is included with the
matplotlib distribution and will be installed automatically if you
don't already have it. The dateutil package provides an rrule module
for generating recurrance rules. Thus you can place ticks every
Monday at 5PM, every 5th easter, on specified hours, weekdays etc.
All of matplotlib's date tick locators utilize rrules under the hood
(see <a href=matplotlib.ticker.html>matplotlib.ticker</a> and <a
href=matplotlib.dates.html>matplotlib.dates</a> for more
information on date ticking).<p>
Here is an example setting up a ticker to make major ticks every year,
minor ticks every month
<pre>
years = YearLocator() # every year
months = MonthLocator() # every month
yearsFmt = DateFormatter('%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
</pre>
The <a href=matplotlib.dates.html#DateFormatter>DateFormatter</a>
class takes an <a
href=http://www.python.org/doc/current/lib/module-time.html>strftime</a>
format string. The example above used the default constructors for <a
href=matplotlib.dates.html#YearLocator>YearLocator</a> and <a
href=matplotlib.dates.html#MonthLocator>MonthLocator</a>. But you can
customize this behavior. For example, to make major ticks every 5
years, and minor ticks on March, June, September and December, you
would do instead
<pre>
# every 5 years
years = YearLocator(5)
# every quarter
months = MonthLocator(range(3,13,3))
</pre>
The date tick locators MinuteLocator, HourLocator, DayLocator,
WeekdayLocator, MonthLocator, and YearLocator are provided, and are
simple interfaces to the rrule generator. See <a
href=examples/pylab_examples/date_demo1.py>date_demo1.py</a> and <a
href=examples/pylab_examples/date_demo2.py>date_demo2.py</a>. For full control of
date ticking, you can use your own rrule with the <a
href=matplotlib.dates.html#RRuleLocator>RRuleLocator</a> class. See
<a href=examples/pylab_examples/date_demo_rrule.py>date_demo_rrule.py</a>. <p>
<table @plot_table_border@><tr><td>
<table>
<caption><h4>A simple plot</h4></caption>
<tr><td valign=top><img src=tut/date_demo2.png></td></tr>
<tr><td valign=top halign=left>
Example code in <a
href=examples/pylab_examples/date_demo2.py>date_demo2.py</a>.
</td></tr>
</table>
</td></tr>
</table><br>
<h4>timezones with pytz</h4>
Timezone support is provided via the <a
href=http://pytz.sourceforge.net/>pytz</a> module. This module
provides python datetime tzinfo implementations of 546 of the Olsen
database timezones. pytz is included in the matplotlib distribution
and will be installed if you don't already have it. Thus you can
reside in Zimbabwe and use matplotlib to plot financial quotes in
London or New York, with correct handling of idiosyncrasies like
daylight savings time. The default timezone is set by the timezone
parameter in your <a href=matplotlibrc>matplotlibrc</a> file. The
timezone is specified as a string acceptable to the pytz.timezone
constructor, eg 'US/Eastern' or 'Europe/London'. The default timezone
in the rc file that ships with matplotlib is 'UTC'. Note, matplotlib
supports per directory rc files, so if you have a project in a
timezone other than your own, you can place an rc file in a working
directory for that project to use that as the default timezone.<p>
All of the matplotlib date ticking classes and functions, except for
drange and date2num, accept an optional argument <tt>tz</tt> which is
a tzinfo instance; the reason drange and date2num do not use it is
because they can infer it from the tzinfo of the supplied datetime
instances. If tz is None (the default) the rc value will be used.
See <a href=examples/pylab_examples/date_demo_convert.py>date_demo_convert.py</a> for
an example date plot using timezone information.
@footer@