Menu

[r472]: / trunk / htdocs / tutorial.html.template  Maximize  Restore  History

Download this file

743 lines (602 with data), 26.4 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=matplotlib.matlab#-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.matlab.html#-colors>color</a> arg'),
    ('data_clipping', 'Whether to use numeric to clip data'),
    ('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 as much of the <a
href=http://lists.sourceforge.net/mailman/listinfo/matplotlib-users>python
tutorial</a> and <a
href=http://lists.sourceforge.net/mailman/listinfo/matplotlib-users>numeric
python manual</a> as possible before working with matplotlib.
Otherwise you may get frustrated.  When you feel comfortable with
both, you'll find matplotlib easy.

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 matplotlib.matlab import *
plot([1,2,3,4])
show()
        </pre>
    </td></tr>
</table>
</td></tr>
</table><br>

<a href=matplotlib.matlab.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 matplotlib.matlab 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.matlab.html#-plot>plot</a> documentation for a
complete list of line styles and format strings.  The <a
href=matplotlib.matlab.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://www.pfdubois.com/numpy>Numeric</a> arrays.  In fact, all
sequences are converted to Numeric arrays internally.  The example
below illustrates a plotting several lines with different format
styles in one command using Numeric arrays.  Note if you are not
familiar with Numeric, now would be a good time to check out their
documentation at <a href=http://www.pfdubois.com/numpy>numpy</a> since
a lot of the matplotlib examples assume you know Numeric, and the
matplotlib.matlab imports all the Numeric (and MLab) functions.<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 matplotlib.matlab 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> for the current line
documentation.<p>

There are several ways to set line properties
<pre>
# Use keyword args - requires matplotlib-0.51 or later.
# Multiple keyword args are allowed 
plot(x, y, linewidth=2.0)  

# plot returns a list of Line2D instances
lines = plot(x, y, 'o')
line1 = lines[0]             # get the first line
line1.set_antialiased(False) # turn off antialising

# The example below uses matlab handle graphics style command
# to set multiple properties on a list of lines
lines = plot(x1, y1, x2, y2) 
set(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>

<a name=figs_and_axes>
<h3>Working with multiple figure and axes</h3>
</a>

Matlab, and matplotlib.matlab, 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.matlab.html#-gca>gca</a> returns the current axes as
an <a href=matplotlib.axes.html#Axes>Axes</a> instance, and <a
href=matplotlib.matlab.html#-gcf>gcf</a> returns the current figure as
a <a href=matplotlib.backend_bases.html#FigureBase>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 matplotlib.matlab 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.matlab.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.matlab.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.matlab.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/axes_demo.py>axes_demo.py</a> for an example of placing
axes manually and <a href=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.matlab.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 matplotlib.matlab import *

figure(1)                # the first figure window
plot([1,2,3]) 
figure(2)                # a second figure window
plot([4,5,6])

figure(1)                # figure 1 is again the current figure
title('Easy as 1,2,3')   # figure 1 title
show()
</pre>

You can clear the current figure with <a
href=matplotlib.matlab.html#-clf>clf</a> and the current axes with 
<a
href=matplotlib.matlab.html#-cla>cla</a>

<a name="text">
<h3>Working with text</h3>
</a>

All of the text commands (<a
href=matplotlib.matlab.html#-xlabel>xlabel</a>, <a
href=matplotlib.matlab.html#-ylabel>ylabel</a>, <a
href=matplotlib.matlab.html#-title>title</a>, and <a
href=matplotlib.matlab.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.matlab.html#-set>set</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 matplotlib.matlab 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.matlab.html#-set>set</a> command to set any of the
properties listed in the table above.  For example, to make a red bold
<a href=matplotlib.matlab.html#-xlabel>xlabel</a>, you would use<p>

<pre>
t = xlabel('time')
set(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 = get(gca(), 'xticklabels')
set(labels, 'color', 'r', 'fontweight', 'bold')
</pre>


<h4><a name=oo>Controlling text using object methods</a></h4>

The <a href=matplotlib.matlab.html#-set>set</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 matplotlib.matlab 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.matlab.html#-text>text</a> command uses color black
with the color string 'k'.<p>


<h4><a name=mathtext>Writing mathematical expressions</aa></h4>

As of matplotlib-0.51, 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.

<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) = $\cal{A}\rm{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>\\rm</tt>, italics <tt>\\it</tt>, caligraphy
<tt>\\cal</tt>, and typewriter <tt>\\tt</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 matplotlib.matlab 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'$\cal{A}\rm{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/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>

These 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<p>

<table>

The Forward and Back 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 'back' on your web browser before
visiting a new page.  Nothing happens.  'Home' always takes you to the
first view.  For Home, Forward and Back, think web browser where data
views are web pages.  Use the pan and zoom to rectangle to define new
views.<p>

The "Pan" button has two modes: pan and zoom.  Click this toolbar
button to activate this mode.  Then put your mouse somewhere over an
axes.  Mode 1: 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.  Mode 2:
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.  In Mode 2, 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.<p>

The Zoom to rectangle button: 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.<p>

Save: 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 in, 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.matlab.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 and toolbar</tt> can be
customized this way dyanmically.  See <a
href=matplotlib.matlab.html#-rc>rc</a> for more information.



<a name="axes_prop">
<h3>Controlling axes properties</h3>
</a>

The <a href=matplotlib.matlab.html#-axes>axes</a> and <a
href=matplotlib.matlab.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=figure.html#Axis>Axis</a>
API.  Or if you prefer matlab handle graphics commands, you can use
the <a href=matplotlib.matlab.html#-set>set</a> to control axis
properties.<p>


<pre>
subplot(111)
plot([1,2,3])
glines = get(gca(), 'gridlines')
set(glines, 'color', 'b', 'linewidth', 2)  # make the gridlines blue
                                           # and thicker
frame = gca(gca(), 'frame')  # get the patches.Rectangle instance
set(frame, 'linewidth', 2)   # increase the linewidth of the rectangular
                             # axis frame
</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.matlab.html#-gca>gca</a> returns a handle to the
current axis<p>

<pre>
subplot(211)
plot([1,2,3], [1,2,3])
set(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.
There are known incompatiblities with some of the backends with 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. You will have the
greatest likelihood of success if you work interactively from the
standard python shell or using <a
href=http://ipython.scipy.org>ipython</a>.  You must use the TkAgg
backend to work interactively from either of these two shells.<p>

As described <a href=tutorial.html#figs_and_axes>above</a> in working
with multiple figures and axes, you can create an arbitrary number of
figures and use the <a href=matplotlib.matlab.html#-figure>figure</a>,
<a href=matplotlib.matlab.html#-subplot>subplot</a>, <a
href=matplotlib.matlab.html#-axes>axes</a>, <a
href=matplotlib.matlab.html#-clf>clf</a>, <a
href=matplotlib.matlab.html#-cla>cla</a>, and <a
href=matplotlib.matlab.html#-close>close</a> command to switch back
and forth, clear and control the figures and axes. <p>

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.matlab.html#-mpl_connect>mpl_connect</a> and <a
href=matplotlib.matlab.html#-mpl_disconnect>mpl_disconnect</a> methods of
the matlab 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
mpl_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>
    <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 matplotlib.matlab 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

mpl_connect('motion_notify_event', on_move)

show()

</pre>




@footer@


Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.