plot_table_border = 'border=1 cellspacing=1 cellpadding=1' font_props = ( ('alpha', 'The alpha transparency on 0-1 scale'), ('color', 'a matplotlib color 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 color 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@
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 matplotlib examples subdirectory. If you are working with date plots you'll find several date demos with obvious filenames like examples/date_demo1.py. Likewise, you'll find examples for images examples/image_demo.py, contouring examples/contour_demo.py, using matplotlib with a graphical user interface examples/embedding_in_wx.py and many more. Because these are not included with the standard windows installer, they are often overlooked, which is why I emphasize them here.
The next place to turn to find the hidden gems is the what's new 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.
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 matplotlibrc, in which you can set whether you want to just create images or use a GUI (the backend setting), and whether you want to work interactively from the shell (the interactive setting). Also, please read interactive use, What's up with show?, and My matplotlib window is freezing 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.
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.
Here is about the simplest script you can use to create a figure with matplotlib
|
plot is a versatile command, and will take an arbitrary number of arguments. For example, to plot x versus y, you can issue the command
plot([1,2,3,4], [1,4,9,16])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 The Mathworks). For example, to plot the above with red circles, you would issue
|
If matplotlib were limited to working with lists, it would be fairly useless for numeric processing. Generally, you will use numpy 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.
|
There are several ways to set line properties
# 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)
Property | Values |
---|---|
@prop@ | @values@ |
>>> lines = plot([1,2,3]) >>> setp(lines)
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
|
You can create multiple figures by using multiple figure calls with an increasing figure number. Of course, each figure can contain as many axes and subplots as your heart desires.
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()You can clear the current figure with clf and the current axes with cla
The text commands return an Text 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
Property | Values |
---|---|
@prop@ | @values@ |
Here is an example adding text to a simple plot
|
t = xlabel('time') setp(t, color='r', fontweight='bold')Set also works with a list of text instances. The following changes the properties of all the tick labels.
labels = getp(gca(), 'xticklabels') setp(labels, color='r', fontweight='bold')
t = xlabel('time') t.set_color('r') t.set_fontweight('bold')
|
Any text element can use math text. You need to use raw strings (preceed the quotes with an 'r'), and surround the string text with dollar signs, as in TeX. Regular text and mathtext can be interleaved within the same string.
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".
# plain text title('alpha > beta') # math text title(r'$\alpha > \beta$')To make subscripts and superscripts use the '_' and '^' symbols, as in
title(r'$\alpha_i > \beta_i$')You can also use a large number of the TeX symbols, as in \infty, \leftarrow, \sum, \int; see mathtext 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
text(1, -0.6, r'$\sum_{i=0}^\infty x_i$')The default font is italics for mathematical symbols. To change fonts, eg, to write "sin" in a Roman font, enclose the text in a font command, as in
text(1,2, r's(t) = $\mathcal{A}\mathrm{sin}(2 \omega t)$')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:
text(1,2, r's(t) = $\mathcal{A}\sin(2 \omega t)$')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 \mathrm, italics \mathit, caligraphy \mathcal, and typewriter \mathtt. If using the STIX fonts, you also have the choice of blackboard (double-struck) \mathbb, circled \mathcircled, Fraktur \mathfrak, script (cursive) \mathscr and sans-serif \mathsf.
The following accents are provided: \hat, \breve, \grave, \bar, \acute, \tilde, \vec, \dot, \ddot. All of them have the same syntax, eg to make an overbar you do \bar{o} or to make an o umlaut you do \ddot{o}.
|
Classic toolbar
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 either 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!
![]() |
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. |
![]() |
The new toolbar2 |
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 matplotlibrc for more information.
You can also dynamically change the defaults in a python script or interactively from the python shell using the rc command. For example to change the default line properties, you could do
>>> rc('lines', linewidth=2, color='r')And the default lines would be thicker and red. All rc parameters except backend, numerix, interactive, toolbar, timezone and datapath can be customized this way dyanmically. See rc for more information.
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)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 gca returns a handle to the current axis
subplot(211) plot([1,2,3], [1,2,3]) setp(gca(), xticklabels=[]) subplot(212) plot([1,2,3], [1,4,9])and the same with instance methods
a1 = subplot(211) plot([1,2,3], [1,2,3]) a1.set_xticklabels([]) subplot(212) plot([1,2,3], [1,4,9])
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
def click(event): print 'you clicked', event.x, event.y #register this function with the event handler connect('button_press_event', click)Then whenever the user clicks anywhere on the figure canvas, your function will be called and passed a MplEvent instance. The event instance will have the following attributes defined.
Property | Meaning |
x | x position - pixels from left of canvas |
y | y position - pixels from bottom of canvas |
button | button pressed None, 1, 2, 3 |
inaxes | the Axes instance if mouse is over axes (or None) |
xdata | x coord of mouse in data coords (None if mouse isn't over axes) |
ydata | y coord of mouse in data coords (None if mouse isn't over axes) |
name | The string name of the event |
canvas | The FigureCanvas instance the event occured in |
key | The key press if any, eg 'a', 'b', '1'. Also records 'control and 'shift' |
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()
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 API_CHANGES 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.
There are three datetime conversion functions: date2num, num2date and drange. 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.
date1 = datetime.date( 1952, 1, 1 ) date2 = datetime.date( 2004, 4, 12 ) delta = datetime.timedelta(days=100) dates = drange(date1, date2, delta)The function plot_date 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 plot. 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.
# make up some random y values s = rand(len(dates)) plot_date(dates, s)
Here is an example setting up a ticker to make major ticks every year, minor ticks every month
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)The DateFormatter class takes an strftime format string. The example above used the default constructors for YearLocator and MonthLocator. 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
# every 5 years years = YearLocator(5) # every quarter months = MonthLocator(range(3,13,3))The date tick locators MinuteLocator, HourLocator, DayLocator, WeekdayLocator, MonthLocator, and YearLocator are provided, and are simple interfaces to the rrule generator. See date_demo1.py and date_demo2.py. For full control of date ticking, you can use your own rrule with the RRuleLocator class. See date_demo_rrule.py.
|
All of the matplotlib date ticking classes and functions, except for drange and date2num, accept an optional argument tz 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 date_demo_convert.py for an example date plot using timezone information. @footer@