Home
The Matplotlib User's Guide
Contents
1. 004 Joh tlib VE nD the eve SE AGREEMENT Lice ny de ter dis Hun is between the John D Hunter r Organization Licensee accessing and otherwise using tware in source or binary fo s and conditions of nsee a nonexclusive royalty free world wide license nt Licensee prepares a derivative wo PPLOTLIB VERSION JDH and the rm and its associated this License Agreement JDH r display publicly prepare right i e Copyright c rk that is based on or incorporates matplotlib VERSION or any part thereof and wants to make t he derivative work available to others as p rovided herein then Licensee hereby agrees to include in any such work a brief summary of the changes made to matplotlib VERSION 4 IS IMP FOR WILI LIED DISCLAIMS A JDH is making JDH MAKES NO REPRESENTATIONS OR WARRA BY WAY OF EXAMPLE BUT NOT LIMITATION JDH MAKES RRANTY OF MERCHANTABILITY THE USE OF MATPLOTLIB VE RIGHTS basis Y REP ANY PARTICULA L NOT INFRINGE 5 JDH SHALL NOT VERSION FOR ANY I LOSS AS A RESULT OF MODIFYING DISTRIBUTING OR OTHERWISE USING atplotlib VE RESENTATION O ANY THIRD PA BE LIABLE TO CIDENTAL SP R PURPOSE OR THAT LICE RSIO R WA RTY ECIAL SEE OR ANY OTHER USERS OF n an AS RESS OR O AND OR FITNESS RSION Licensee o TIES EXP available to F MATPLOTLIB ES OR OR CONSEQUENTI
2. This file is best viewed in a editor which supports python mode syntax highlighting Blank lines or lines starting with a comment symbol are ignored as are trailing comments Other lines must have the format Cal optional comment Colors for the color values below you can either use a matplotlib color string such as r k or b an teb tuple such as 01 0 0 39 00 a hex string such as ff00ff no symbol a scalar grayscale intensity such as 0 75 a legal html color name eg red blue darkslategray H HH HH HF HF HF HF HF HF HF HF HHH HH HH FH CONFIGURATION BEGINS HERE the default backend one of GTK GTKAgg GTKCairo FltkAgg QtAgg TkAgg Agg Cairo GD GDK Paint PS PDF SVG Template backend Agg numerix numpy numpy Numeric or numarray interactive False see http matplotlib sourceforge net interactive html toolbar toolbar2 None classic toolbar2 timezone UTE a pytz timezone string eg US Central or Europe Paris Where your matplotlib data lives if you installed to a non default location This is where the matplotlib fonts bitmaps etc reside datapath home jdhunter mpldata LINES 73 See http matplotlib sourceforge net matplotlib lines html for more information on line properties lines linewidth LAO line width in points lines linestyle 2 solid line lines color IS lines marker None the default marker lines mar
3. mec r ms 40 mew 4 Is lw 3 If you are not using ipython pylab then by default matplotlib defers drawing until the end of the script because drawing can be an expensive operation Often you don t want to update the plot every time a single property is changed only once after all the properties have changed But in interactive mode eg from the standard python shell you usually do want to update the plot with every command eg after changing the xlabel or the marker style of a line To do this you need to set interactive True in your configuration file see Section 2 6 13 There are many python shells out there the standard python shell ipython PyShell pysh pycrust Some of these are GUI dependent PyShell pycrust and some are not ipython pysh As discussed in backends Section 2 3 not all shells are compatible with all matplotlib backends because of GUI mainloop issues With a non GUI python shell such as the standard python shell or pysh the TkAgg backend is the best choice for interactive use Just set backend TkAgg and interactive True in your matplotlibrc file and fire up python Then using matplotlib interactively from the python shell gt gt gt from pylab import gt gt gt plot 1 2 3 gt gt gt xlabel hi mom should work out of the box Note in batch mode ie when making figures from scripts interactive mode can be slow since it redraws the figure with each command So you
4. bolg sizes x large alignment axis 1 1 0 1 savefig figures fonts_demo_kw png 46 savefig figures fonts_demo_kw eps show 47 48 Chapter 5 Collections 49 50 Chapter 6 Tick locators and formatters The matplotlib ticker module contains classes to support completely configurable tick locating and formatting Although the locators know nothing about major or minor ticks they are used by the Axis class to support major and minor tick locating and formatting Generic tick locators and formatters are provided as well as domain specific custom locators an formatters 6 1 Tick locating Choosing tick locations and formats is a difficult and essential part of making nice looking graphs The matplotlib ticker module divides the workload between two bases classes the locators and the formatters Each axis eg the xaxis and yaxis has a major and minor tick locator and a major and minor tick formatter The default minor tick locators always return the empty list ie there are no minor ticks Each of these can be set independently and it is easy for the user to create and plug in a custom tick locator or formatter The matplotlib ticker Locator class is the base class for all tick locators The locators handle autoscaling of the view limits based on the data limits and choosing the tick locations The most generally useful tick locator is MultipleLocator You initialize this with a
5. Figure 8 2 The inheritance diagram for The FigureCanvas hierarchy The FigureCanvas is a backend dependent class which contains a figure instance For GUI backends the canvas should be a GUI widget embeddable in a GUI window Some of the GUIs have backends with both native drawing and antigrain drawing GTK GTKAgg WX WX Agg which is readily achieved with multiple inheritance Line 1 from pylab import x When any matplotlib code is imported the first time the matplotlib __init__ py code is called The primary thing the init code does is find and parse your re file or if it fails fall back on a set of default parameters Once this is done pylab proceeds to import all of the matplotlib numerix and matplotlib mlab symbols into the namespace and loads the backend from matplotlib backends which use the rc information to load four functions from the backend module specified by the rc backend parameter The pylab interface requires only four functions from the backend new_figure_manager error_msg draw_if_interactive and show The pylab interface also imports a Gcf instance from the matplotlib _matlab_helpers module which manages the current figure and current axes The pylab interface defines gcf and gca to get a reference to the current figure and new_figure_manager is responsible for creating a new instance from a backend dependent class derived from matplotlib backend_bases FigureManager this class wraps GUI window creation and manage
6. X 0 t X 5 ll amp save data ascii_data dat X 3 4 2 Loading and saving binary data ASCII is bloated and slow for working with large arrays and so binary data should be used if performance is a consideration To save the array X in binary form use the numerix tost ring method open the file for writing binary and write the binary string file data binary_data dat wb write X tostring This data can later be loaded into a numerix array using fromst ring This method takes two arguments a string and a data type note that numarray users can use fromfile which is more efficient for importing data directly from a file load the data as a string S fille fdata simary_caracat 7297 renal 23 convert to 1D numerix array of type Float X fromstring s Float reshape to numSamples rows by 2 columns X shape len X 2 2 t X 0 the first column s X 1 the second row Doils 8 07 Note that although Numerix and numarray use different typecode arguments Numeric uses strings whereas numarray uses type objects the matplotlib numerix compatibility layer provides symbols which will work with either numerix rc setting 3 4 3 Processing several data files Since python is a programming language par excellence it is easy to process data in batch When I started the grad ual transition from a full time MATLAB user to a full time python user I began processing m
7. axes labelcolor black axes axisbelow als whether axis gridlines and ticks are below ae es elemen e limes e ele axes formatter limits 7 7 use scientific notation if logl0 of the axis range is smaller than the first or larger than the second polaraxes grid GUS display grid on polar axes 75 TICKS see http matplotlib sourceforge net matplotlib axis html Ticks xtick major size 4 major tick size in points xtick minor size 2 minor tick size in points xtick major pad 8 distance to major tick label in points xtick minor pad 8 distance to the minor tick label in points xtick color k color of the tick labels xtick labelsize 12 fontsize of the tick labels xtick direction in direction in or out ytick major size 4 major tick size in points ytick minor size 2 minor tick size in points ytick major pad 8 distance to major tick label in points ytick minor pad 8 distance to the minor tick label in points ytick color k color of the tick labels ytick labelsize 12 fontsize of the tick labels ytick direction in 4 dineetioners nsorzout GRIDS grid color 2 black grid color grid linestyle dotted grid linewidth 0 5 in points HHH Legend legend isaxes GUS legend numpoints 22 the number of points in the legend line legend fontsize 14 legend pad 0 the fractional whitespace inside the legend border legend markersc
8. see List ing 3 3 Listing 3 3 Custom axes see Figure 3 7 from pylab import create some data to use for the plot dt 0 001 t arange 0 0 10 0 dt r exp t 1000 0 05 impulse response x randn len t s convolve x r mode 2 len x dt colored noise the main axes is subplot 111 by default plot t s axis 0 1 1 1 min s 2 max s xlabel time s ylabel current nA 28 title Gaussian colored noise this is an inset axes over the main axes A BES OD 07 lt 2 oAll misg y n bins patches hist s 400 normed 1 title Probability setp a xticks yticks tt this is another inset axes over the main axes a axes 0 2 0 6 2 2 axisbg y plot t len r r title Impulse response setp a xlim 0 2 xticks yticks 3 6 Text matplotlib has excellent text support including newline separated text with arbitrary rotations and mathematical ex pressions freetype2 support produces very nice antialiased fonts that look good even at small raster sizes It includes its own font_manager thanks to Paul Barrett which implements a cross platform W3C compliant font finding algo rithm You have total control over every text property font size font weight text location and color etc with sensible defaults set in the rc file And significantly for those interested in mathematical or scientific figures matplotlib imple men
9. text 0 8 yp k family k family family k name Script MT x xxalignment else Il text 0 8 yp k family k family family k alignment Show style options style mormal italie oblique t text 0 4 0 9 style xxalignment for k in range 3 t text 0 4 yp k style k family sans serif style style k alignment Show variant options variant normal small caps t text 0 0 0 9 variant alignment for k in range 1 t text 0 0 yp k variant k family serif variant variant k alignment Show weight options weiging lige normal medina semibole bold ineawy Ioilack t text 0 4 0 9 weight xx alignment for k in range 7 t text 0 4 yp k weight k weight weight k alignment Show size options size seegmaiil osa small Yimechiia large Crailawege elare t text 0 8 0 9 size xxalignment for k in range 7 t text 0 8 yp k size k size size k x alignment x 0 Show bold italic i texti Mel sole deal e styles deal weight bold size x small alignment i Ext 0 2 hold dtailie style italie Weilgiiia bold Sime mackium s alignment fi Ext Mei sole dralie siyles italic weiginis
10. you can blend images even on backends which don t support alpha eg postscript This is because the alpha blending is done in the frontend and the blended image is transferred directly to the backend as an RGB pixel array See Recipe 7 4 2 for an example of how to layer images 3 7 2 Figure images Often times you want to be able to look at your raw image data directly without interpolation This is the function of figure images which do a pixel by pixel transfer of your image data to the figure canvas Figure images are drawn first and thus can become the background of other matplotlib drawing commands In the pylab interface figure images are created with the figimage command which unlike imshow does not accept an interpolation or aspect keyword argument because no image resampling is used If the pixel extent of the figure image extends beyond the figure canvas the image will simply be truncated The basic syntax is figimage X xo 0 yo 0 where X is luminance MxN RGB MxNx3 or RGBA MxNx4 numerix array and xo yo are pixel offsets from the origin see Section 3 7 4 You can use figimage to create a figure image that fills the entire canvas with no x or y offsets or you can make multiple calls to figimage with different x and y offsets to create a mosaic of images as shown in Recipe 7 4 3 The full syntax of the figimage command is figimage X the numerix array xo 0 the x offset yo 0 A they offset alpha 1 0 the al
11. 0 1 scale color A matplotlib color arg family set the font family eg sans serif cursive fantasy fontangle the font slant one of normal italic oblique horizontalalignment left right or center multialignment left right or center only for multiline strings name the font name eg Sans Courier Helvetica position the x y location variant the font variant eg normal small caps rotation the angle in degrees for rotated text size the fontsize in points eg 8 10 12 Style the font style one of normal italic oblique text set the text string itself verticalalignment top bottom or center weight the font weight eg normal bold heavy light Table 3 4 Properties of matplotlib text Text See the example http matplotlib sourceforge net examples fonts_demo_kw py which makes extensive use of font properties for more information See also Chapter 4 for more discussion of the font finder algorithm and the meaning of these properties 3 6 3 Text layout You can layout text with the alignment arguments horizontalalignment verticalalignment and multialignment hor izontalalignment controls whether the x positional argument for the text indicates the left center or right side of the text bounding box verticalalignment controls whether the y positional argument for the text indicates the botto
12. 3 5 3 axes When you need a finer grained control over axes placement than afforded by subplot use the axes command The axes command in initialized with a rectangle left bottom width height in relative figure coordinates 27 left bottom 0 0 is the bottom left of the of the figure canvas and a width height of 1 spans the figure width height This to create an axes that entirely fills the figure canvas you would do axes 0 1 0 1 This may not be a good idea because it leaves no room for text labels axes 0 25 0 25 0 5 0 5 creates an axes offset by one quarter of the figure width and height on all sides There are several ways to use the axes command in all cases a matplotlib axes Axes instance is returned e axes by itself creates a default full subplot 111 window axis e axes rect axisbg w where rect left bottom width height in normalized 0 1 units axisbg 1s the background color for the axis default white e axes ax where axis an axes instance makes ax current gca returns the current axes instance and cla clears the current axes You can use the axes command lay the axes exactly where you want them including to overlaying one axes on top of another as in this example Gaussian colored noise 0 03 Impulse response Probability 0 02 current nA o 2 o o 36 0 01 0 0 0 2 0 4 0 6 0 8 1 0 time s Figure 3 7 Using the axes command to create inset axes over another axes
13. 8 by 8 chessboard Zl array 0 1 4 1 0 4 4 Zl shape 8 8 iml imshow Z1 cmap cm gray interpolation nearest extent extent prevents the axes from clearing on next command hold True Z2 func3 X Y im2 imshow Z2 cmap cm jet alpha 9 interpolation bilinear extent extent mas ac 7 4 3 Creating a mosaic of images You can compose several figure images into a mosaic using the figimage command as discussed Section 3 7 2 If your hold state is True multiple calls to figimage X xo yo xo and yo are the pixel offsets from the origin the origin can be either upper left or lower left as discussed in Section 3 7 4 The code below using color mapping to place two images on the diagonal Note that you can use different kinds of arrays luminance RGB RGBA and different colormaps when creating figure mosaics See Figure 7 5 Figure 7 5 Creating a mosaic using figimage see Listing 7 5 Listing 7 5 Creating figure mosaics see Figure 7 5 from pylab import rc axes hold True 62 rc image origin upper Z arange 40000 0 Z shape 200 200 Zale 303 iml figimage Z xo 0 yo 0 im2 figimage Z xo 100 yo 100 alpha 8 7 4 4 Defining your own colormap Perry Greenfield has provided a nice framework with matplotlib colors LinearSegmentedColormap to define new colormaps You can create new colormaps fairly easy by following the example of jet in matplot
14. Ss S SSe EELE FESS PSL IF SIF EPL CLS Figure 6 2 Providing custom tick locators and formatters for financial date plots see Listing 6 2 Listing 6 2 Custom date tick locators and formatters see Figure 6 2 import datetime from pylab import from matplotlib dates import MONDAY SATURDAY from matplotlib finance import quotes_historical_yahoo from matplotlib dates import MonthLocator WeekdayLocator DateFormatter from matplotlib ticker import FormatStrFormatter the start and end date range for the financial plots datel datetime date 2003 1 1 date2 datetime date 2004 4 12 the tick locators and formatters mondays WeekdayLocator MONDAY every monday months MonthLocator every month monthsFmt DateFormatter b d looks like May 01 dollarFmt FormatStrFormatter 0 2 dollars get some financial data from the finance module 54 quotes quotes_historical_yahoo INTC datel date2 if not quotes raise SystemExit failsafe extract the date and opening prices from the quote tuples dates q 0 for q in quotes opens q 1 for q in quotes plot_date will choose a default date ticker and formatter ax subplot 111 plot_date dates opens markeredgecolor k tt but we ll override the default with our custom locators and formatters ax xaxis set_major_locator months ax xaxis set_major_formatter monthsFmt ax xaxis set_minor_locator mondays fo
15. and by matplotlib in Figure 3 9 RTI aisin 2T fxi 3 1 i Q Listing 3 5 Using mathtext see Figure 3 9 from matplotlib import rcParams rcParams ps useafm False from pylab import use a custom axes to provide room for the large labels used below az eslo 225 ola Ml Aaa y generate some random symbols to plot x rand 40 plot x 1 x 1 go markeredgecolor k markersize 14 33 141 Figure 3 9 Incorpating TEX expressions into your figure see Listing 3 5 this is just a made up equation that has nothing to do with the plot S rn Sica Hint jowocl N alliolua yemi aisla E Noi dE x iS text 0 2 1 2 s fontsize 20 axis 0 2 1 2 0 2 1 8 subscripts superscripts and groups with are supported usetex If you have IAT X ghostscript and dvipng installed on your computer matplotlib can use IATRXto perform all of the text layout in your figures To enable this option set text usetex True in your rc settings For more information and examples see http www scipy org Cookbook Matplotlib UsingTex 3 7 Images matplotlib provides support for working with raw image data in numerix arrays Currently there is no support for loading image data from image files such as PNG TIFF or JPEG though this is on the TODO list If you need to load data from existing image files one good solution is to use The Python Imaging Library to load the data and convert this to a nume
16. are installing matplotlib to a non standard location Eg if you install matplotlib with python setup py build prefix home jdhunter then set matplotlib data to home jdhunter share matplotlib e After all that if it cannot find your rc file it will issue a warning and use defaults This is not recommended 2 6 3 In the event of a problem matplotlib uses a verbose setting defined in the matplotlibre file to determine how much information to report verbose level error one of silent error helpful debug debug annoying verbose fileo sys stdout a log filename sys stdout or sys stderr verbose erro sys stderr a log filename sys stdout or sys stderr These settings control how much information matplotlib gives you at runtime and where it goes The verbosity levels are silent error helpful debug debug annoying Atthe error level you will only get error messages Any level is inclusive of all the levels below it Ie if your setting is helpful you ll also get all the error messages If you setting is debug you ll get all the error and helpful messages It is not recommended to make your setting silent because you will not even get error messages You can access the verbose instance in your code from matplotlib import verbose The verbose fileo setting gives the destination for any calls to the verbose report function The verbose erro setting gives the destination for any calls to verbose error reporting function These ob
17. convert PIL image gt string convert string gt numerix array of floats rgb fromstring s Ulnt8 astype Float 255 0 resize to RGB array rgb resize rgb im size 1 im size 0 3 imshow rgb interpolation nearest axis off don t display the image axis show 7 4 2 Blending several axes images using alpha You can compose several axes images on top of one another using alpha blending as described in Section 3 7 1 If your hold state is True multiple calls to imshow will cause the image arrays to be resampled to the axes bounding box and blended Of course the uppermost images must have alpha less than one or else they will be fully opaque and hence the lower images will be invisible Note that you can blend images from arrays of different shapes as well as blending images with different colormaps and interpolation schemes The example below creates a black and white checkboard using a grayscale colormap and then blends a color image over it as shown in Figure 7 4 Figure 7 4 Layering axes images using alpha blending see Listing 7 4 Listing 7 4 Alpha blending multiple images see Figure 7 4 from pylab import def func3 x y return 1 x 2 0 xxx 5 yx x3 xexp x r2 yx x2 make these smaller to increase the resolution dx dy 0 05 0 05 61 x arange 3 0 3 0 dx y arange 3 0 3 0 dy X Y meshgrid x y extent min x max x min y max y make an
18. gt gt gt from pylab import gt gt gt figure gt gt gt subplot 111 gt gt gt plot 1 2 3 3 5 1 figure You can create and manage an arbitrary number of figures using the figure command The standard way to create a figure is to number them from 1 N A callto figure 1 creates figure 1 if it does not exist makes figure 1 active gcf will return a reference to it and returns the matplotlib figure Figure instance The syntax of the figure command is 24 def figure num 1 figsize None defaults to rc figure figsize dpi None defaults to rc figure dpi facecolor None defaults to re figure facecolor edgecolor None defaults to re figure edgecolor frameon True whether to draw the figure frame Ve figsize gives the figure size in inches and is width by height Eg to create a figure 12 inches wide and 2 inches high you can call figure figsize 12 2 dpi gives the dots per inch of your display device Increasing this number effectively creates a higher resolution figure facecolor and edgecolor determine the face and edge color of the figure rectangular background This is what gives the figure a gray background in the GUI figures such as Figure 2 1 You can turn this background completely off by setting frameon False The default for saving figures is to have a white face and edge color and all of these properties can be customized using the rc parameters figure and savefig In typical usage
19. majorFormatter FormatStrFormatter d integer format string minorLocator MultipleLocator 5 multiples of 5 my favorite plot t arange 0 0 100 0 0 1 s sin 0 1 pixt exp t 0 01 ax subplot 111 plot t s now just set the major and minor locators and formatters ax xaxis set_major_locator majorLocator ax xaxis set_major_formatter majorFormatter for the minor ticks use no labels default NullFormatter ax xaxis set_minor_locator minorLocator 53 6 4 Example 2 date ticking Making nice date time plots requires custom tick locating and formatting matplotlib converts all datetimes to days since 0001 01 01 and uses a floating point number to represent fractions of days The functions date2num and num2date are used to convert back and forth between python datetimes and these floating point numbers The example below uses the matplotlib finance module to get some historical quotes from yahoo s historical quotes server The datetime start and end points are specified using a python s datetime module Major ticks are on the months MonthLocator and minor ticks are on Mondays WeekdayLocator Only the major ticks are la belled using a strftime format string DateFormatter Finally since the y axis is a stock price a string formatter Format StrFormatter is used to place dollar signs on the y tick labels 35 00 30 00 25 00 20 00 15 00 10 00 S RS S S SS S gt gt gt S SN gt gt
20. several datafiles o s ro 2 Coon o AA ee BEE ee N Boel PAGO ANA ou peg he ele He Jod E de Sethe BAA hk dk Gets i Boys CGS soo 4 haw ee Soe A RA Bo ewe ew eS O SO NOM cease a GS oe eee a So eo OR a rer ae Sedu hs ak ib Gee Bae PS 3 6 Basic text commands a Oe Oe A Ew aw Se TEO o chad brates Ge aie te Bae Ghee te Bee ee eins e ae 33 TIERNO onc ee ka fee eR RRR EE RR Pe owen es SS SLE ELE ES RS NO WAME o Dah te Ge evened te de erie beh amp a whee be Bh eee 5 Bele WWA os oye IDAS EES Pht es EMD ES EE Se BA ee he Beas Bull o os anog a aed a AN au oO SO NO 11 11 12 13 14 14 15 15 15 16 AN ec EI 36 4 7 3 Scaling and color mapping c sc g oe ee ea a ee a ea a 36 37 4 mage OTP sonso seg Ss e ee a BR A ee See i 37 3 8 Barcharts histograms and ertorbar plots o r ecs a ee y 8 we en ee ee 38 39 Pserdocolorand Scaler PO s e rec e 2 pa a a oa ee Eee PORE ee ees 38 3 10 Spectr lanalye s pes ppe Kee ee a e epe he ea eee aa hE eee e 38 Sok AKEP esa di dc e o eS Ee e a EE BAS 40 212 Legends and tables rs See e HES AS a A es WE RES Se ee A 40 AS AMIE ABO A A 40 Selo Classic Toolbar e aci eee ek ar Gap Sed He ga ta ie eg Bose a 40 AAD 2 AGODA 2 a Re A ae Ae ew ae ea ea ee A 40 3 14 Event handling gt s e ora ea a o EA en GO Se Bled Bee i 42 3 15 Customizing plotdefanlts 6 54 404224 ob eae eM E ee A EERE ERE EDS 43 Font finding and properties 45 Collections 49 Tick locators and formatters 51 61 Tick
21. state When hold is on subse quent plotting commands are superimposed over previous commands When hold is off the plot is cleared with every plotting command This is controlled by the hold command which can be called like hold True or hold False The default setting is in matplotlibrc as axes hold True which you can change according to your preferences 18 To clear the previous plot and reissue the plot command for just the sine wave you can use cla to clear the current axes and clf to clear the current figure or simply turn the hold state off gt gt gt hold False gt gt gt plot t s 3 2 More on plot 3 2 1 Multiple lines plot is a versatile command and will create an arbitrary number of lines with different line styles and markers This example plots a sine wave and a damped exponential using the default line styles gt gt gt clf clear the figure gt gt gt t arange 0 0 5 0 0 05 gt gt gt sl sin 2xpixt gt gt gt s2 sl x exp t gt gt gt plot t sl t s2 If you plot multiple lines in a single plot command the line color will cycle through a list of predefined colors The default line color and line style are determined by the rc parameters lines style and lines color You can include an optional third string argument to each line in the plot command which specifies any of the line style marker style and line color To plot the above using a green dashed line with circle markers and
22. that you distribute across platforms Do you need a GUI interface Each of the python GUIs work on all major platforms but some are easier than others to install Each have different advantages GTK is natural for linux and has excellent looking widgets but is a tough install on OS X Tkinter is deployed with most python installations but has primitive looking widgets wxpython has native widgets but can be difficult to install Windows users note the enthought edition of python from http www enthought com python comes with Tkinter and wxpython included Now that Qt 4 has been released under the GPL for windows the Qt backend is a new alternative with cross platform compatibility What features do you need Some of the matplotlib features including alpha blending antialiasing images and mathtext are not ported to all backends Agg and the Agg hybrids support all matplotlib features agg is a core matplotlib backend Postscript native GTK and native WX do not support alpha or antialiasing SVG supports everything except mathtext which will hopefully be supported soon Do you need dynamic images such as animation The GUI backends vary in their ability to support rapid updating of the image canvas GTKAgg is currently the fastest backend for animation with FLTKAgg a close second Once you have decided on which backends you want to use make sure you have installed the required GUI toolkits and devel versions if you are using a package ma
23. you may want to consider using the Enthought edition of python which includes everything you need to start plotting with matplotlib Enthought s Python distribution also includes a lot of other goodies like the wxPython GUI toolkit and SciPy see http www enthought com python For standard Python installations you should install NumPy before running the matplotlib installer The windows installer exe on the download page contains everything else you need to get up and running We highly recommend installing PyReadline and Python as well see http ipython scipy org The Tk GUI toolkit is generally included with standard python installations There are many examples that are not included in the matplotlib windows installer They can be found at http matplotlib sourceforge net matplotlib_examples_0 87 7 zip 2 1 2 Package managers rpms apt fink RPMS To build all the backends on a binary linux distro such as redhat you need to install a number of the devel libs and whatever dependencies they require I suggest e matplotlib core zlib zlib devel libpng libpng devel freetype freetype devel freetype utils e gtk backend gtk2 devel gtk devel pygtk2 glib devel pygtk2 devel gnome libs devel pygtk2 libglade e tk backend tcl tk tkinter e wx wxagg backend The wxpython rpms Debian and Ubuntu Vittorio Palmisano lt redclay email it gt maintails the debian packages at http mentors debian net He pro vid
24. you will only provide the figure number and let your rc parameters govern the other figure attributes gt gt figure 1 gt gt gt plot 1 2 3 gt gt figure 2 gt gt gt plot 4 5 6 gt gt gt title big numbers Migure 2 title gt gt figure 1 gt gt gt title small numbers figure 1 title You can close a figure simply by clicking on the close x in the GUI window or by issuing the close command close can be used to close the current figure a figure referenced by number a given figure instance or all figures e close by itself closes the current figure e close num closes figure number num e close fig where fig is a figure instance closes that figure e close all closes all the figure windows If you close a figure directly eg close 2 the previous current figure is restored to the current figure clf is used to clear the current figure without closing it If you save the return value of the figure command you can call any of the methods provided by matplotlib figure Figure for example you can set the figure facecolor gt gt gt fig figure 1 gt gt gt fig set_facecolor g or use set for the same purpose gt gt gt set fig facecolor g 3 5 2 subplot axes and subplot are both used to create axes in a figure subplot is used more commonly and creates axes assuming a regular grid of axes numRows by numCols For example to create two rows and one column of
25. AL DAMAG 81 MATPLOTLIB VERSION OR ANY DERIVATIVE THEREOF EVEN IF ADVISED OF THE POSSIBILITY THEREOF 6 This License Agreement will automatically terminate upon a material breach of its terms and conditions 7 Nothing in this License Agreement shall be deemed to create any relationship of agency partnership or joint venture between JDH and Licensee This License Agreement does not grant permission to use JDH trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee or any third party 8 By copying installing or otherwise using matplotlib VERSION Licensee agrees to be bound by the terms and conditions of this License Agreement 82 Bibliography Julius S Bendat and Allan G Piersol Random Data Analysis and Measurement Procedures John Wiley amp Sons New York 1986 Eric W Weisstein CRC Concise Encyclopedia of Mathematics Chapman amp Hall CRC second edition edition 2002 83
26. Python we recommend getting accustomed to the language by experimenting with some of the tutorials at http wiki python org moin BeginnersGuide Programmers or by reading one of the several books intro ducing Python for example Mark Lutz and David Ascher s Learning Python Finally matplotlib does not intend to meet the needs of MATLAB users alone Many matplotlib users previously worked with gnuplot for example and have influenced matplotlib s features based on their previous experience Our 7 goal is to provide a flexible powerful library that is capable of easily producing beautiful plots for scientists and engineers who work with Python Chapter 2 Installation and Setup 2 1 Installing Matplotlib is known to work on linux unix win32 and OS X platforms This chapter will begin with basic installation instructions to help new users get going quickly The suggested setup for matplotlib version 0 87 7 and later requires python 2 3 or later NumPy 1 0 or later and freetype If you are using python 2 3 matplotlib also requires setup tools which can be installed by running http peak telecommunity com dist ez_setup py setuptools is not required for python 2 4 and later For interactive use of matplotlib we recommend installing Python and at least one of the GUI toolkits We suggest using the Tk GUI toolkit if you are just getting started 2 1 1 Quickstart on windows If you don t already have python installed
27. The Matplotlib User s Guide John Hunter and Darren Dale March 3 2007 Contents 1 Introduction 11 Migrating from MATLAB 22 26 5 a aus corrida a 2 Installation and Setup 2 1 EI 2 1 1 Quckst ll ON WINdOWS os cx ee ee Ra A ee a ee ea ee ee 2 1 2 Package managers ps apt DE o o c e 2 een 2 13 Compiling matplothb c s lt sere 588 46 Dba RE He eee eee eae 214 Toal Rie ea 2 88820 a E AS A Sm ee AAA ee A E 22 Backend a a A A a A a a GSS 2 3 Intesrated development environments csa ce Sy a Bae SUA a AS O a AE Ae Pe Se ee od Nena NN 23 NUMER o CA eR Hh se Oa Re SS 2 5 1 Choosing Numeric numarray or NumPy o 0002220005 2 6 Customization using matplotlibre cssc ea ee ee tT u eera be 261 RE Metoimat pi chalk eeoa a A Qe NR a hk oh Bee BLS 262 Which te fle istis d o 24 54 x 24 5264 5 48 ERA AA Ph da ER 26 5 Inthe eventoraproblem 222 22 4 nen ew Ge ee aS 3 The pylab interface Dol DIME PIGS a ee eee A Ge ge eee ee Se ee Se ee Ee ne 32 MORON P O bn kb kas ke ee OE A A EAS Dawe a PERS SR OD EER SS 321 Multiple dines i i por mas eee ee RE RAE ERR eee ER ES 32 2 Controlling line properties 5 se tukea kaia ee a eS Da COOP ATEN fc ok A a ch a RLS Ge Re BSA ee eh GL G 34 Loading and savmg data ec ee be EV Ree ew eee ee eee es 3 4 1 Loading and saving ASCII data 2 2 2 2 0 0 02 eee ee eee eee 34 2 Loading and saving binary data sp ca ns ap anna as ni ar 3 4 3 Processing
28. There are many GUIs for python pygtk wxpython Tkinter PyQT pyfltk and more and matplotlib supports most of them In choosing your backend the following considerations are important e What kind of output do you require Any matplotlib installation can generate PS and SVG For other hardcopy formats different backends have different capabilities Agg can only generate png but produces the highest quality output antialiased alpha blending The native GTK and WX backends support many more image formats JPG TIFF but can only be used in GUI mode and produce lower quality images The GUI hybrid backends WXAgg GTKAgg Tkagg FLTKAgg QtAgg Qt4Agg have the same capabilities and limitations as Agg 11 e Do you want to produce plots interactively from the python shell Most GUIs have a mainloop and become unresponsive to outside input once they are launched Thus you often need to use a custom shell to work interactively with a GUI application from the shell pycrust for wx PyShell for gtk A notable exception is Tkinter which can be controlled from a standard python shell or ipython Fernando Perez the author of ipython has written a pylab mode for ipython that lets you use WX GTK Qt Qt4 or Tk based backends interactively from the python shell If you want to work interactively with matplotlib the recommended approach is to use ipython What platform do you use most frequently Do you want to embed matplotlib in an application
29. a red dotted line with circle markers as shown in Figure 3 3 gt gt gt clf gt gt ploi i O tw 82 E28 gt gt gt legend sine wave damped exponential Figure 3 3 All line plots take an optional third string argument which is composed of optionally a line color eg r g K a line style eg and a line marker o s d The sine wave line green dashed line with circle markers is created with g o The legend command will automatically create a legend for all the lines in the plot The color part of the format string applies only to the facecolor of 2D plot markers like circles triangles and squares The edgecolor of these markers will be determined by the default rc parameter lines markeredgecolor and can be defined for individual lines using the methods discussed below 19 3 2 2 Controlling line properties In the last section we showed how to choose the default line properties using plot format strings For finer grained control you can set any of the attributes of a matplotlib lines Line2D instance There are three ways to do this using keyword arguments calling the line methods directly or using the set command The line properties are shown in Table 3 1 Property Value alpha The alpha transparency on 0 1 scale antialiased True or False use antialised rendering color A matplotlib color arg data_clipping Whe
30. able fonts small caps is equivalent to using a font size of smaller or about 83 The font weight property has effectively 13 values normal bold bolder lighter 100 200 300 900 Normal is the same as 400 and bold is 700 bolder and lighter are relative values with respect to the current weight The font stretch property has 11 values ultra condensed extra condensed condensed semi condensed normal semi expanded expanded extra expanded ultra expanded wider and narrower This property is not currently implemented The font size property is the default font size for text given in pts 12pt is the standard value Special text sizes for tick labels axes labels title etc can be defined relative to font size using the following values xx small x small small medium large x large xx large larger or smaller Special text sizes can also be an absolute size given in pts Here is an example using the font properties to illustrate the different fonts from matplotlib import rcParams rcParams ps useafm False from pylab import subplot 111 axisbg w 45 alignment horizontalalignment center verticalalignment center Show family options family V serii sems serit enesive fantasy monospace t text 0 8 0 9 family size large x alignment yp 0 7 0 5 0 3 0 1 0 1 0 3 0 5 for k in range 5 ii ik se 2 t
31. ale 0 the relative size of legend markers vs original the following dimensions are in axes coords legend labelsep 0 010 the vertical space between the legend entries legend handlelen ROBOS AI E E NS legend handletextsep 0 02 the space between the legend line and legend text legend axespad 0 02 the border between the axes and legend edge tlegend shadow 2 False FIGURE See http matplotlib sourceforge net matplotlib figure html Figure figure figsize 2 y figure size in inches figure dpi z BO figure dots per inch figure facecolor 0 75 figure facecolor 0 75 is scalar gray figure edgecolor white figure edgecolor The figure subplot parameters All dimensions are fraction of the figure width or height figure subplot left 0 125 the left side of the subplots of the figure figure subplot right 0 9 the right side of the subplots of the figure figure subplot bottom 0 1 the bottom of the subplots of the figure figure subplot top 0 9 the top of the subplots of the figure figure subplot wspace 0 2 the amount of width reserved for blank space between subplots figure subplot hspace 0 2 the amount of height reserved for white space between subplots 76 IMAGES image aspect equal equal auto a number image interpolation bilinear see help imshow for options image cmap 3 pat a ray et Gia image lut 256 the size of the color
32. an be a pain too many keystrokes The matplotlib lines Line2D class provides a number of abbreviated method names listed in Table 3 2 Thus you can for example call no antialiasing gt gt gt plot range 10 thick green markeredge lines ro aa False mew 2 mec g 21 3 3 Color arguments matplotlib is fairly tolerant of a number of formats for passing color information As discussed above you can use and of the single character color strings listed in Table 3 3 Additionally anywhere a color character string is accepted you can also use a grayscale hex RGB color argument or any legal hml color name ebg red or darkslategray voltage mV 0 0 0 2 0 4 0 6 0 8 1 0 time s Figure 3 5 Lots of different ways to specify colors generated from Listing 3 1 not necessarily recommended for aesthetic quality Listing 3 1 Wild and wonderful ways to specify colors see Figure 3 5 from pylab import axis background in dark slate gray subplot 111 axisbg 0 1843 0 3098 0 3098 t arange 0 0 1 0 0 01 s sin 2x2xpixt yellow circles with red edge color plot t s yo markeredgecolor r lAbel cime s coOll rs in xlabel is blue ylabel voltage mV color 0 5 ylabel is light gray title Don t try this at home folks color afeeee 3 4 Loading and saving data pylab provides support for loading and saving ASCII arrays or vectors w
33. anspose of X and the 1 superscript denotes the inverse For more info see Mathworld but note that the k s and n s in the superscripts and subscripts on that page are problematic The linear algebra is correct however Inttp mathworld wolfram com LeastSquaresFittingPolynomial html 59 polynomial regression Figure 7 3 Estimating a best fit cubic for some random data see Listing 7 3 Listing 7 3 est fit polynomial see Figure 7 3 from pylab import Generate some test data y is a poly function of x nse x arange 0 0 2 0 0 05 nse 0 6xrandn len x y 1 1 3 2xx 0 l x 2 2 xX 3 nse t the bestiit line from polyfit coeffs polyfit x y 3 plot the data with blue circles and the best fit with a thick solid black line besty polyval coeffs x plot x y bo x besty k linewidth 2 ylabel polynomial regression grid True 7 4 Working with images 7 4 1 Loading existing images into matplotlib Currently matplotlib only supports plotting images from numerix arrays either luminance RGB or RGBA If you have some existing data in an image file format such as PNG JPEG or TIFF you can load this into matplotlib by first loading the file into PIL http www pythonware com products pil and then converting this to a numerix array using fromstring tostring methods import Image from pylab import 60 im Image open data leo_ratner jpg s im tostring
34. answer is 51 lambdaS are not currently supported A large set of the TEX symbols from the computer modern fonts are provided Subscripting and superscripting are supported as well as the over under style of subscripting with sum int etc Note that matplotlib does not use or require that TEX be installed on your system as it does not use it Rather it uses the parsing module pyparsing to parse the TEX expression and does the layout manually in the matplotlib mathtext module using the font information provided by matplotlib ft2font The spacing elements and hspace num are provided inserts a small space and hspace num inserts a fraction of the current fontsize Eg if num 0 5 and the fontsize is 12 0 hspace 0 5 inserts 6 points of space 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 6 you do bar o or to make an you do ddot o The shortcuts are also provided eg Wo Ve Ve n x Vy 32 Licensing The computer modern fonts this package uses are part of the BaKoMa fonts which are in my understanding free for noncommercial use For commercial use please consult the licenses in fonts ttf and the author Basil K Maly shev see also http www mozilla org projects mathml fonts encoding license bakoma txt and the file BaKoMa CM Fonts in the matplotlib fonts dir Note that all the code in this module is distributed under th
35. atplotlib backend_bases FigureCanvasBase and contains the matplotlib figure Figure instance Once the current axes is obtained by gca plot forwards the call to Axes plot If an exception is raise the backend 69 new_figure_manager returns FigureManagerGTK contains window gtk Window canvas FigureCanvasGTK ontains figure Figure Figure 8 5 The pylab interface function new_figure_manager returns a backend dependent concrete implementation of matplotlib backend_bases FigureManagerBase which contains the figure canvas and figure window The attribute names are shown in lower case and the backend dependent classes are shown in upper case The standard attribute naming system allows the MATLABTM interface to make calls across backends to the figure canvas and figure error_msg method is called with the traceback to display it Ifthe code is successful the backend draw_if_interactive method is called which will update the plot if the rc parameter interactive is True and finally the return value is returned def plot xargs xkwargs try lines gca plot xargs kwargs except ValueError msg msg raise_msg_to_str msg error_msg msg else draw_if_interactive return lines plot __doc__ Axes plot __doc__ The matplotlib axes Axes plot method parses the args and kwargs creates the requested line objects and adds them to its list of Line2D instances It will also extract the x a
36. axes you would use subplot 211 to create the upper axes and subplot 212 to create the lower axes The last digit counts across the TOWS 25 A tale of 2 subplots Damped oscillation Undamped time s Figure 3 6 Multiple rows of axes created with the subplot command as shown in List ing 3 2 Listing 3 2 Generating multiple axes with subplot see Figure 3 6 from pylab import def f t a damped oscillation return cos 2 pixt exp t tl t2 arange 0 0 arange 0 0 0 1 5 0 5 0 0 02 the upper subplot 2 rows 1 column subplot 1 subplot 211 le plloi il EL 799 2 FCI ke grid True title A tale of 2 subplots ylabel Damped oscillation the lower subplot 2 rows 1 column subplot 2 subplot 212 plot t2 cos 2xpixt2 r gt grid True xlabel time s ylabel Undamped Likewise to create two columns and one row of axes you would use subplot 121 to create the left axes and subplot 122 to create the right axes If the total number of axes exceeds single digits use comma separated arguments to subplot For example the lower right panel of a 3 x 4 grid of axes is created with subplot 3 4 12 matplotlib uses MATLAB style indexing in creating figures and axes so subplot 3 4 1 is the first subplot not subplot 3 4 0 26 The subplot command returns a matplotlib axes Subplot instance which is derived from matplotlib axes Axe
37. base eg 10 and it picks axis limits and ticks that are multiples of your base The class AutoLocator contains a MultipleLocator instance and dynamically updates it based upon the data and zoom limits This should provide much more intelligent automatic tick locations both in figure creation and in navigation than in prior versions of matplotlib See Tables 6 1 and 6 2 for a summary of the basic and date tick locators Class Summary NullLocator No ticks IndexLocator locator for index plots eg where x range len y LinearLocator evenly spaced ticks from min to max LogLocator logarithmically ticks from min to max MultipleLocator ticks and range are a multiple of base either integer or float AutoLocator choose a MultipleLocator and dynamically reassign Table 6 1 The basic tick locators You can define your own locator by deriving from Locator You must override the __call__ method which returns a sequence of locations and you will probably want to override the autoscale method to set the view limits from the data limits If you want to override the default locator use one of the above or a custom locator and pass it to the x or y axis instance The relevant methods are ax xaxis set_major_locator xmajorLocator ax xaxis set_minor_locator xminorLocator 51 Class Summary MinuteLocator locate minutes HourLocator locate hours DayLocator locate specifed days of the month WeekdayLocator Locate days of t
38. bus Roman No9 L Times New Roman Times Palatino Charter serif font sans serif Bitstream Vera Sans Lucida Grande Verdana Geneva Lucid Arial Helvetica Avant Garde sans serif font cursive Apple Chancery Textiler Zap Chancery Sand Cursive font fantasy Comic Sans MS Chicago Charcoal Impact Western fantasy font monospace Bitstream Vera Sans Mono Andale Mono Nimbus Mono L Courier New Courier Fixed Terminal monospace TEXT text properties used by text Text Ses http matplotlib sourceforge net matplotlib text html for more information on text properties text color black text usetex False use latex for all text handling For more Information see http www scipy org Wiki Cookbook Matplotlib UsingTex text dvipnghack False some versions of dvipng don t handle alpha channel properly Use True to correct and flush matplotlib tex cache before testing AXES deramllo ace and edee color detalle Miele Sizes default ftontsizes for ticklabels ands so on SES http matplotlib E net matplotlib axes html Axes axes hold rue whether to clear the axes by default on axes facecolor white axes background color axes edgecolor black axes edge color axes linewidth ree LEO edge linewidth axes grid False display grid or not axes titlesize 14 o VOMSIZe OF me es titie axes labelsize 12 fontsize of the x any y labels
39. d builds the backend accordingly If you have installed prerequisites to nonstandard places and need to inform matplotlib where they are edit setu pext py an add the base dirs to the basedir dictionary entry for your sys platform Eg if the header to some required library is in some path include somheader h put some path in the basedir list for your platform Note that if you install matplotlib anywhere other than the default location you will need to setthe MATPLOTLIBDATA environment variable to point to the install base dir Eg if you install matplotlib with python setup py build prefix home 3jdhunter then set MATPLOTLIBDATA to home jdhunter share matplotlib OSX All of the backends run on OS X fink users consult the fink discussion in section 2 1 2 Another option is http www stecf org macosxscisoft which packages many scientific packages for python on OS X including matplotlib although it is designed for astronomical analysis If you want to compile matplotlib yourself on OS X make sure you read the compiling instructions in section 2 1 3 You will need to install freetype2 libpng and zlib via fink or from src You will also need the base libraries for a given backend Eg if you want to run TkAgg you will need a python with Tkinter if you want to use WxAgg install wxpython See Section 2 2 for a more comprehensive discussion of the various backend requirements Note when running a GUI backend in OS X you should launch yo
40. e 7 1 from pylab import xl arange 0 2 0 01 yl sin 2xpixxl y2 sin 4 pixxl 2 reverse x and y2 so the polygon fills in order x concatenate xl x1 1 y concatenate yl y2 1 p fill x y facecolor g 7 2 Text 7 2 1 Adding a ylabel on the right of the axes To make a ylabel on the right use the text command You need to set the transform to use axes coordinates ax transAxes rotate the text vertically make the horizontal alignment left the vertical alignment centered Note that x y 1 0 5 is the right middle of the axes in axes coordinates You also need to turn off clipping so the text can appear outside the axes w o being clipped by the axes bounding box which is the default behavior 57 3 0 2 5 2 0 MAL 0 5 2 0 0 0 0 5 1 0 0 0 0 5 1 0 1 5 Figure 7 1 Fill the area between two curves see Listing 7 1 text T02 5 O 5 moltsa horizontalalignment left verticalalignment center rotation vertical transform gca transAxes clip_on False 7 3 Data analysis 7 3 1 Linear regression One of the most common tasks in analyzing data is a linear regression of one variable on another matplotlib provides polyfit in the matplotlib mlab module for general polynomial regression Listing 7 2 Best fit line see Figure 7 2 from pylab import Generate some test data y is a linear function of x nse x arange 0 0 2 0 0 05 nse 0 3xrandn le
41. e font variant property has two values normal or small caps For TrueType fonts which are scalable fonts small caps is equivalent to using a font size of smaller or about 83 of the current font sizer The font weight property has effectively 13 values normal bold bolder lighter 100 200 300 900 Normal is the same as 400 and bold is 700 bolder and lighter are relative values with respect to the current weight The font stretch property has 11 values ultra condensed extra condensed condensed semi condensed normal semi expanded expanded extra expanded ultra expanded wider and narrower This property is not currently implemented H HHHHHHHHHHHHH HHH HHH HF HF HF HF HF HF HF HF HH FH 74 The font size property is the default font size for text given in pts 12pt is the standard value font family sans serif font style normal font variant normal font weight medium font stretch normal note that font size controls default text sizes To configure Special ext Sizes Wek labels axes labels tiile s Cie SEG tine ire settings for axes and ticks Special text sizes can be defined relative to font size using the following values xx small x small small medium large x large xx large larger or smaller font size e 120 font serif Bitstream Vera Serif New Century Schoolbook Century Schoolbook L Utopia ITC Bookman Bookman Nim
42. e matplotlib license and a truly free implementation of mathtext for either freetype or ps would simply require deriving another concrete implementation from the Fonts class defined in this module which used free fonts Using mathtext 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 plain text title alpha gt beta math text title r alpha gt beta To make subscripts and superscripts use the underscore and caret symbols as in mile r Salma at gt bera s7 You can also use a large number of the TEX symbols as in infty leftarrow sum int see Appendix B for a complete list The over under subscript superscript style is also supported To write the sum of x from 0 to o 0x you could do text l 0 6 r S sum_ i 0 intty x 19 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 cal A rm sin 2 omega t Here s and r are variable in italics font default sin is in roman font and the amplitude 4 is in caligraphy font The fonts cal rm it and tt are allowed Fairly complex TEX expressions render correctly you can compare the expression s r cal R prod_ i alpha infty a_i rm sin 2 Api f x_i rendered by TEX below
43. e view limits of the axes in the figure toolbar2 superceeds classic and was designed to overcome shortcomings of the classic toolbar The default toolbar is determined by the toolbar parameter in matplotlibrc 3 13 1 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 Figure 3 13 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 3 13 2 toolbar2 The toolbar2 buttons see Figure 3 14 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 40 A tale of 2 subplots o oooo SS oo n nDaPenoneame Damped osci
44. er left pass origin upper and with the image in the lower left pass origin lower as shown in Figure 3 11 Listing 3 7 Setting the image origin see Figure 3 11 from pylab import x arange 100 0 x shape 10 10 subplot 211 37 blue should be up 10 2 0 0 2 4 6 8 10 m blue should be down 8 Figure 3 11 Controlling the image origin with the origin keyword argument to imshow and figimage see Listing 3 7 title blue should be up imshow x origin upper interpolation nearest subplot 212 title blue should be down imshow x origin lower interpolation nearest 3 8 Bar charts histograms and errorbar plots Use the bar function to create simple bar plots The simplest form of this function is simply bar x y which creates bars with their left edge at x and height y There are a number of options to support more sophisticated bar plots including stacked bar plots and bar plots with errorbars The signature of the bar method is def bar left height width 0 8 bottom 0 color b yerr None xerr None ecolor k capsize 3 3 9 Pseudocolor and scatter plots 3 10 Spectral analysis matplotlib provides a number of MATLABTM compatible functions for computing and plotting spectral analysis re sults All of them are based on Welch s Averaged Periodogram Method Bendat and Piersol 1986 using the numerix fft method for the fast fourier trans
45. es the following instructions e add these lines to your etc apt sources list deb http anakonda altervista org debian packages deb sre http anakonda altervista org debian sources e then run gt apt get update gt apt get install python matplotlib python matplotlib doc Alternatively Andrew Straw maintains an Apt Repository of scientific Python packages e add these lines to your etc apt sources list deb http debs astraw com dapper deb src http debs astraw com dapper fink fink users should use Jeffrey Whitaker s matplotlib fink package which includes support for the GTK Tk and WX GUI toolkits see http fink sourceforge net pdb package php matplotlib py23 or http fink sourceforge net pdb package php matplotlib py24 orhttp fink sourceforge net pdb package php matplotlib py25 2 1 3 Compiling matplotlib You will need to have recent versions of freetype gt 2 1 7 libpng and zlib installed on your system If you are using a package manager make sure the devel versions of these packages are also installed eg freetype devel If you want to use a GUI backend you will need either Tkinter pygtk PyQt PyQt4 or wxpython installed on your system either from source or a package manager including the devel packages You can choose which backends to enable by setting the flags in setup py but the auto flags will work in most cases as matplotlib checks the availability of each GUI toolkit an
46. ever plotted with MATLABTM and should be fairly straightforward if you haven t Like all interpreted languages used for serious number crunching python has an extension module for processing numeric arrays This python extension module is called Numpy NumPy comes with many MATLAB compatible analysis functions which matplotlib extends The example code below shows two complete scripts on the left hand side is python with matplotlib and on the right is MATLABTM vel F H A N A 4 N l NN y IVANA 0 15 7 u 0 1 2 3 4 5 6 ES 8 9 10 ven nya meN a 70 1 i 0 5 10 15 20 25 30 35 40 45 50 Frequency 20 Power Spectrum Magnitude dB Figure 1 1 Colored noise signal and power spectrum generated with MATLAB as shown in Listing 1 1 Compare with matplotlib in Figure 1 2 Both scripts do the same thing generate a white noise vector convolve it with an exponential function add it to a sine wave plot the signal in one subplot and plot the power spectrum in another Listing 1 1 matplotlib and MATLAB python matlab from pylab import x no import necessary dt 0 01 dt 0 01 t arange 0 10 dt t 0 dt 10 nse randn len t nse randn size t r exp t 0 05 r exp t 0 05 cnse conv nse r xdt cnse conv nse r xdt cnse cnse len t ense cnse l length t s 0 1 sin 2 pixt cnse s 0 1 sin 2 pixt cnse subplot 211 subplot 211 plot t s
47. forms The spectral plotting functions are psd for the power spectral density csd for the cross spectral density and cohere for the coherence normalized cross spectral density 38 signature and defaults for arguments to a typical spectral analysis function def psd x NFFT 256 Fs 2 detrend mlab detrend_none window mlab window_hanning noverlap 0 In addition to the time series arguments x y these functions take a number of optional parameters The averaged periodogram method chops the time series into NFFT length segments which overlap by noverlap samples The default values are NFFT 256 and noverlap 0 Each of the functions will compute the spectral analysis and then generate a plot window with frequency on the x axis if you want the frequency axis to be properly scaled you should provide the sampling frequency Fs Each of the segments will be detrended and windowed before the fft according to the values of detrend and window Unlike MATLAB in which these arguments are strings in matplotlib they are functions Several helper functions are provided in matplotlib mlab for detrending and windowing e mlab detrend_none no detrending e mlab detrend_mean remove the mean of each segment before fft e mlab detrend_linear remove the best fit line of each segment before fft e mlab window_none no windowing e mlab window_hanning multiply each segment by a Hanning window An example power spectra calculation is sh
48. he week eg MO TU MonthLocator locate months eg 7 for july YearLocator locate years that are multiples of base RRuleLocator locate using a matplotlib dates rrulewrapper The rrulewrapper is a simple wrapper around a dateutils rrule https Table 6 2 The tick locators specialized for date plots these reside in the matplotlib dates module ax yaxis set_major_locator ymajorLocator ax yaxis set_minor_locator yminorLocator The default minor locator is the NullLocator eg no minor ticks on by default 6 2 Tick formatting Tick formatting is the process of converting the numeric tick location into a suitable string and is controlled by classes derived from matplotlib ticker Formatter The formatter operates on a single tick value and its tick position and returns a string to the axis The tick formatters are summarized in Table 6 3 Class Summary NullFormatter no labels on the ticks FixedFormatter set the strings manually for the labels FuncFormatter user defined function sets the labels FormatStrFormatter use a sprintf format string IndexFormatter cycle through fixed strings by tick position ScalarFormatter default formatter for scalars autopick the fmt string LogFormatter formatter for log axes DateFormatter use an strftime string to format the date Table 6 3 The tick formatting classes You can derive your own formatter from the Formatter base class by simply overriding the __call__ method The forma
49. interface that knows nothing about output The backends are device dependent drawing devices aka renderers that transform the frontend representation to hardcopy or a display device Example backends PS creates postscript hardcopy SVG creates scalar vector graphics hardcopy Agg 5 creates PNG output using the high quality antigrain library that ships with matplotlib http antigrain com GTK embeds matplotlib in a GTK application GTKAgg uses the antigrain renderer to create a figure and embed it a GTK application and so on for WX Tkinter Qt FLTK matplotlib is used by many people in many different contexts Some people want to automatically generate postscript files to send to a printer or publishers Others deploy matplotlib on a web application server to generate PNG output for inclusion in dynamically generated web pages Some use matplotlib interactively from the python shell in Tkinter on windows My primary use is to embed matplotlib in a GTK EEG application that runs on windows linux and OS X Because there are so many ways people want to use a plotting library there is a certain amount of complexity inherent in configuring the library so that it will work naturally the way you want it to Before diving into these details let s first explore matplotlib s simplicity by comparing a typical matplotlib script with its analog in MATLAB JDH 1 1 Migrating from MATLAB Using matplotlib should come naturally if you have
50. it with the value you pass If set_something does not exist then an exception will be raised Using matplotlib lines Line2D methods You can also call Line2D methods directly The return value of plot is a sequence of matplotlib lines Line2D instances Note in the example below I use tuple unpacking with the to extract the first element of the sequence as line line plot t s1 gt gt gt line plot t sl gt gt gt line set_markersize 15 gt gt gt line set_marker d 20 gt gt gt line set_markerfacecolor g gt gt gt line set_markeredgecolor r Note however that we haven t issued any pylab commands after the initial plot command so the figure will not be redrawn even though interactive mode is set To trigger a redraw you can simply resize the figure window a little or call the draw method The fruits of your labors are shown in Figure 3 4 gt gt gt draw 1 0 o 3 3 3 e o oo Figure 3 4 Large green diamonds with red borders created with three different recipes Abbreviated method names Abbreviation Fullname aa antialiased c color ls linestyle lw linewidth mec markeredgecolor mew markeredgewidth mfc markerfacecolor ms markersize Table 3 2 Abbreviated names for line properties You can use any of the line customiza tion methods above with abbreviated names When working from an interactive python shell typing markerfacecolor c
51. ith the load and save command matplotlib numerix provides support for loading and saving binary arrays with the fromstring and tostring methods 3 4 1 Loading and saving ASCII data Suppose you have an ASCII file of measured times and voltages like so 22 b blue g green r red c cyan m magenta y yellow k black w white 0 75 a grayscale intensity any float in 0 1 2F4F4F an RGB hex color string eg this example is dark slate gray 0 18 0 31 0 31 an RGB tuple this is also dark slate gray red any legal html color name Table 3 3 Color format strings which can be used to set the line or text properties eg the line the marker edgecolor or marker facecolor 0 0000 0 4911 0 0500 0 5012 0 1000 0 7236 0 1500 1 1756 and so on You can load that data into an array X with the load command The shape of X is numSamples rows by 2 columns with the first column containing the time points and the second column containing the measured voltages You can use numerix array indexing to extract the two columns into the 1D arrays t and s X load data ascii_data dat t X 0 the first column s X 1 the second row plot t s o Likewise you can save array or vector data in an ASCII file with the save command The following script was used to create the sample data above from pylab import t arange 0 0 1 0 0 05 s sin 2 pixt 0 5xrand len t X zeros len t 2 Float
52. jects can a filename or a full path to a filename sys stderr or sys stdout You can override the rc default verbosity from the command line by giving the flags verbose LEVEL where LEVEL is one of the legal levels eg verbose error verbose helpful If you run into a problem and want to ask for help or report a bug to the mailing list please set verbose to helpful or debug and paste the output into your report Also please include the shortest possible example code that reproduces the problem With the example code and verbose output other readers of the mailing list have a much better chance of understanding the problem and offering a solution The email address is matplotlib users lists sourceforge net Finally for those who are using the development sources from the sourceforge subversion repository please report problems to matplotlib devel lists sourceforge net instead of matplotlib users lists sourceforge net You can subscribe to either mailing list at http sourceforge net mail group_id 80706 16 Chapter 3 The pylab interface Although matplotlib has a full object oriented API see Chapter 8 the primary way people create plots is via the pylab interface which can be imported with from pylab import This import command brings in all of the matplotlib code needed to produce plots the extra MATLAB compati ble non plotting functions found in matplotlib mlab and all of the matplotlib numerix code needed to create and ma
53. keredgewidth 0 5 the line width around the marker symbol lines markersize 6 markersize in points lines dash_joinstyle miter miterlround bevel lines dash_capstyle butt butt lround projecting lines solid_joinstyle miter miter round bevel lines solid_capstyle projecting buttlround projecting lines antialiased True render lines in antialised no jaggies PATCHES Patches are graphical objects that fill 2D space like polygons or 7 Circles See t http matplotlib sourceforge net matplotlib patches html for more information on patch properties patch linewidth 1 0 edge width in points patch facecolor blue patch edgecolor black patch antialiased ve render patches in antialised no jaggies FONT font properties usediby text Texti See http matplotlib sourceforge net matplotlib font_manager html for more information on font properties The 6 font properties used for font matching are given below with their default values Tine vont famiy property Mas five values seri 6 3 Mimes sans seriti e g Helvetica cursive e g Zapi Chancery fantasy e g Western and monospace e g Courier Each of these font families has a default list of font names in decreasing order of priority associated with them The font style property has three values normal or roman italic or oblique The oblique style will be used for italic if it is not present Th
54. l graphical user interfaces GUIs provide event handling to determine things like key presses mouse position and button clicks matplotlib sup ports a number of GUIs and provides an interface to the GUI event handling via the mp1_connect and mp1_disconnect 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 FigureCanvas mpl_connect method 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 this function will be called with every click def click event print you clicked event x event y register this function with the event handler cid connect button_press_event click Then whenever the user clicks anywhere on the figure canvas your function will be called and passed a matplotlib backend_bases Mp instance The event instance will have the following attributes defined You can connect to the following events button_press_event button_release_event motion_notify_event key_press_event and key_release_event You can connect multiple event handlers and later disconnect them if you want with the disconnect function register this function with
55. lib cm Here are the steps e define your rgb linear segments in matplotlib cm following the lead of the _jet_data dictionary in that module e add an entry to the datad dictionary in that module which maps rc string names for your color map to the dictionary you just defined e instantiate a single instance of your colormap in cm following the example jet colors LinearSegmentedColormap jet _jet_data LUTSIZE e add a pylab function which has the same name as your colormap following the example of pylab jet Now anyone can use the colormap interactively from the shell by setting it as the default image cmap in rc etc Please submit your changes to the matplotlib devel mailing list 75 Output 7 5 1 Printing to standard output In some instances it is nice to be able to print to a file object eg sys stdot for example in a web application server where the creation of a temporary file storing the images is a wasted step The antigrain backend accepts a file object to the savefig command and will print a PNG to it Thus to print to standard output you could do import sys import matplotlib this is not supported across all backends as of matplotlib 0 63 matplotlib use Agg from pylab import x plot 1 2 3 savefig sys stdout 63 64 Chapter 8 Matplotlib API The pylab interface does a lot of work for you under the hood creating and managing multiple figure windows directing your plotting comma
56. llation Undamped o o un o un g 0 5 Is time s ama AA a 7AA Figure 3 13 The classic toolbar discussed in Section 3 13 1 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 Zoomand Zoom to rectangle buttons discussed below to define new views The Pan Zoom button has two modes pan and zoom Click this toolbar button to activate this mode Then put your mouse somewhere over an axes e 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 If you press x or y while panning the motion will be contrained to the x or y axis respectively e 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 The point under your mouse when you begin the zoom should remain i
57. locatime lt o rie rd eA neta eb eee ee ba ee PA Seed eee eee ee See eo 51 Oo JUSTAS sio a o 52 6 3 Example li major and mimorticks se sss 6 carr A rs 52 94 Example dat TERNE e 24 2 2222 ad II A Va Bee Se PR e 54 Cookbook 57 El PlOvelements eea 25 ri a a Dees bi 57 7 1 1 Horizontal or vertical limes spams s e css 2 2 08 a ew es 57 71 2 Fillithe arca Between TWO CUIVES o oos ia Se ni aa a e 57 Ta TE ch eae ee eee ee ee EO KLASSE Paw eee AGE eG A 57 7 2 1 Adding a ylabel on the right of the axes o onen 57 2 3 Data analysis A E RR RAE RR A E SO ee Ee es 58 A a A ea ee De eet eee bye ete eS 58 Vag Polynomial regression spa sp Rena Mw eh ee ee net 59 hee WOES WUhamagER o oec g eke eS SHS SENS u dd de A 60 7 4 1 Loading existing images into matplotlib o o 60 74 2 Blending several axes images using alpha Comm mn 61 TAS Creating mosaic of Images cocido aa a a a Ge 62 7 4 4 Defining your own Coloma 63 To OQU PUL e era e Ge Dh en a Be Ele Bow a 63 75 1 Printing to standard output eeri ceres drunen en A 63 Matplotlib API 65 Sl Dismatplotibibackends s 6 042456 24350 ah oe ESE E Maes 65 8 1 1 The renderer and praphics comiext s e 6 05 54 a a a A ee ee 66 S12 Thefig re canvases o co eee dea EAR AERA Re A A A 67 So The Mpio Tb Artisisu 0 a ee A ann Arten 67 83 pylabinterface internals e 2 2 a ee ce eae A eee bee en 67 A sample matplotlibrc 73 mathtext symbols 79 matplotlib so
58. lotlib internals to give a clearer picture of how things work and how they are orga nized Some of this material may be of interest only to developers but most of it should shed light for anyone who wants to be able to exploit the full capabilities of matplotlib The normal path of figure creation in matplotlib is pylab interface creates artists calls to the backend renderer This section will invert that process starting with the backend which is where the drawing actually takes place This is the natural order of presentation because the back end knows nothing about Artists which in turn known nothing about the pylab interface After the overview of the backend API there is a discussion of the matplotlib artists this is the section that is most useful to users particularly those who want to embed matplotlib in an application The final section shows how the pylab interface controls the backends and artists this section is probably of interest to developers and the terminally curious 8 1 The matplotlib backends The backend consists of a number of related base classes that together define a drawing API The original backend was GTK and the drawing API is heavily based on the GTK drawing model which is very simple There are three essential classes defined in matplotlib backend_bases RendererBase GraphicsContextBase and FigureCanvasBase In addition there are some classes for use with the GUI backends to define the interface to the t
59. m center or top side of the text bounding box multialignment for newline separated strings only controls whether the different lines are left center or right justified Here is an example which uses the text command to show the various alignment possibilities The use of transform ax transAxes throughout the code indicates that the coordinates are given relative to the axes bounding box with 0 0 being the lower left of the axes and 1 1 the upper right Listing 3 4 Aligning text see Figure 3 8 from pylab import from matplotlib patches import Rectangle build a rectangle in axes coords leit waiclils 5 5 bottom height 25 5 right left width top bottom height ax gca p Rectangle left bottom width height fill False axes coordinates are 0 0 is bottom left and 1 1 is upper right p set_transform ax transAxes p set_clip_on False 30 ax ax ax ax ax text left amp N SD right bottom SE right to ww RY pu L a R middle gt ES t bott jef top 2 center top Figure 3 8 Aligning text with horizontalalignment verticalalignment and multialign ment options to the text command see Listing 3 4 add_patch p bottom left top horizontalalignment left verticalalignment top transform ax transAxes text left bottom left bottom horizontalalignment left verticalalignment bottom transform ax tra
60. mage gci to determine which image to apply the commands which affect image properties To interactively set the image normalization limits use clim vmin None vmax None where vmin and vmax have the same meaning as above To interactively change the colormap use jet or gray More colormaps and colormap commands are planned These latter commands not only change the colormap of the current image they also set the default for future images For quantitative plotting of pseduocolor images use the colorbar function to provide a colorbar associated with the image Here is an example interactive session controlling image scaling and color mapping with a colorbar gt gt gt imshow X plot the luminance image X gt gt gt clim 1 2 scale the image gt gt gt jet use colormap jet gt gt gt colorbar add a colorbar to the current axes gt gt gt gray use grayscale image and colorbar are updated The image scaling and color mapping are handled by the mixin base class matplotlib colors ScalarMappable 3 7 4 Image origin Depending on your data it may be more natural to plot your data with the image origin up X 0 0 is upper left or down X 0 0 is lower left matplotlib supports these two modes with the origin parameter which can be supplied as an optional keyword argument to the image commands imshow and figimage with the default set by the rc parameter image origin To plot an image with the origin in the upp
61. map lookup table image origin upper lower upper CONTOUR PLOTS contour negative_linestyle 6 0 6 0 negative contour dashstyle size in points SAVING FIGURES the default savefig params can be different for the GUI backends Eg you may want a higher resolution or to make the figure background white savefig dpi 100 figure dots per inch savefig facecolor white figure facecolor when saving savefig edgecolor white figure edgecolor when saving tk backend params tk window_focus False Maintain shell focus for TkAgg tk pythoninspect False tk sets PYTHONINSEPCT ps backend params ps papersize letter PAULO Le UL ai e er AOAO BOBO ps useafm False use of afm fonts results in small files ps usedistiller ase can be None ghostscript or xpdf Experimental may produce smaller files xpdf intended for production of publication quality files but requires ghostscript xpdf and ps2eps ps distiller res 6000 dpi pdf backend params pdf compression 6 integer from 0 to 9 0 disables compression good for debugging svg backend params svg image_inline True write raster image data directly into the svg file svg image_noscale False suppress scaling of raster data embedded in SVG Set the verbose flags This controls how much information matplotlib gives you at runtime and where it goes Ther verbosity levels are silent helpful debug debug annoyi
62. matplotlib backends RendererBase and then call Figure draw renderer which in turn passes the draw command on to each Artist instance it contains see Figure 8 4 for the Artist contain ment hierarchy Each Artist instance defines the draw method and contains a transform to transform itself to display coordinates For example the Line2D instance will transform its x and y data to display coordinates and then call the appropriate renderer method eg RendererGTK draw_lines which expects x and y data in display coordinates In this case the GTK renderer draw_lines method makes the appropriate calls to the GTK drawing API and the screen 1s updated see Figure 8 6 expose even A reates a backen endent 2 Der t FigureCanvas draw gt e sab d depende C canvas figure draw renderer backend canvas updated for all figures renderer instance Figure 8 6 The typical sequence of steps triggered in the backend code by the call to show that ultimately gets the ink on the canvas 71 72 Appendix A A sample matplotlibrc MATPLOTLIBRC FORMAT This is a sample matplotlib configuration file It should be placed in HOME matplotlib matplotlibre unix linux like systems and C Documents and Settings yourname matplotlib win32 systems By default the installer will overwrite the existing file in the install path so if you want to preserve your s please move it to your HOME dir and set the environment variable if necessary
63. max None the origin None the numerix array matplotlib colors Colormap instance normalization instance aspect setting interpolation method alpha transparency value min for image scaling max for image scaling image origin When None these parameters will assume a default value in many cases determined by the rc setting The meaning of cmap norm vmin vmax and origin will be explained in sections below The following shows a simple command which creates an image using bilinear interpolation shown in Figure 3 10 Figure 3 10 Simple axes image code in Listing 3 6 Listing 3 6 Axes images see Figure 3 10 from pylab import 35 delta 0 025 generate a mesh of x and y vectors x y arange 3 0 3 0 delta X Y meshgrid x y create 2D gaussian distributions Zl bivariate_normal X Y 1 0 1 0 0 0 0 0 Z2 bivariate_normal X Y 1 5 0 5 1 1 plot the difference of Gaussians with blinear interpolation im imshow Z2 Z1 interpolation bilinear mas aor 3 You can create an arbitrary number of axes images inside a single axes and these will be composed via alpha blending However if you want to blend several images you must make sure that the hold state is True and that the alpha of the layered images is less than 1 0 if alpha 1 0 then the image on top will totally obscure the images below Because the image blending is done using antigrain regardless of your backend choice
64. may want to think carefully before making this the default behavior 2 5 Numerix Numeric is the original python module for efficiently processing arrays of numeric data While highly optimized for performance and very stable some limitations in the design made it inefficient for very large arrays and developers decided it was better to start with a new array package to solve some of these design problems Thus numarray was born In a sense this caused the numerical python community to split into Numeric and numarray user groups To resolve this split Travis Oliphant one of the maintainers of Numeric began work on a third package based on the Numeric code base which incorporated the advances made in numarray This project is now called NumPy NumPy is the successor to both Numeric and numarray and is intended to reunite the numerical python community An array interface was developed in order to allow the three array packages to play well together and to easy migration to NumPy Numeric is no longer undergoing active development and the numarray release notes suggest users to switch to Numpy Matplotlib requires one of Numeric numarray or NumPy to operate If you have no experience with any of these packages you are strongly advised to install Numpy and read through some of the documentation before continuing Since the array packages all play well together we expect that in the near future matplotlib will depend on NumPy alone Until then
65. ment error_msg displays an error message for image backends this message is printed to the file object determined by the rc parameter verbose erro and for GUI backends it is typically displayed in a GUI dialog box draw_if_interactive is called after every pylab drawing command plot set xlim and updates the figure window with the new information only if interactive is True show raises all the GUI figure windows and triggers a command to draw the figure 68 EECa CLneColesion Figure 8 3 The matplotlib Artist hierarchy The primitive Artists are the Patches Line2D Text AxesImage Figurelmage and Collection classes All other artists are composites of these For example a Tick is comprised of a Line2D instance and a Text instance which make up the tick line and tick label the Axis is comprised of a list of Ticks and a Text axis label see Figure 8 4 0 07 0 n Mu figurePatch texts images legends Rectangle Text Figurelmage Legend images AxesImage minorTicks Xtick axesPatch Rectangle majorTicks Xtick legendPatch texts handles Rectangle Text Line2D or Patch ticklline Line2D tick2line Line2D label2 Text gridline Line2D Figure 8 4 The Artist containment hierarchy The top level Artist is the matplotlib figure Figure which contains all of the other Artist instances The at tribute names are given in lower case and the object
66. n place 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 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 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 The Save button 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 TIFE which is why I haven t worked too hard to include these other image formats in agg 41 Figure 1 1 0 0 5 0 0 0 5 A 4 O O Bla Figure 3 14 The newfangled toolbar2 discussed in Section 3 13 2 3 14 Event handling When visualizing data it s often helpful to get some interactive input from the user Al
67. n x y 2 3xx nse the bestfit line from polyfit you can do arbitrary order polynomials but here we take advantage of a line being a first order polynomial m b polyfit x y 1 plot the data with blue circles and the best fit with a thick solid black line 58 regression Figure 7 2 Estimating a best fit line for some random data see Listing 7 2 Mot y 907 ka mosto Ak lime ta ylabel regression grid True 7 3 2 Polynomial regression polyfit can also be used for general polynomial fitting The signature of polyfit is coeffs polyfit x y N where N is the order of the polynomial The best fit can be obtained from the coefficients and the x data using best polyval x coeefs coeffs are the coefficients of the polynomial coef fs px P1 Po The algorithm for polyfit is taken from Mathworld s Least Squares Fitting Polynomial and Vandermonde Matrix entries Weisstein 2002 To do a best fit polynomial regression of order N of y onto x We must solve an N dimensional system of equations eg for N 2 po x Pi xot po y paxxttp rx po y p2 x pi x2 po y P2 aX Pi Xk t PO Yk If X is a the Vandermonde Matrix computed from x then the polynomial least squares solution is given by the p in X xp y where X is a x by N 1 matrix pis a N 1 length vector and y is a len x by 1 vector This equation can be solved as p XX xXxy 7 1 where X is the tr
68. nager If you know you don t want a particular backend or extension you can set the appropriate flag to False in setup py Most users will want to keep the setup py default BUILD_AGG 1 Exceptions to this are if you know you don t need a GUI or you only want to produce vector graphics like postscript svg or pdf If you want to produce png output keep BUILD_AGG 1 Then install matplotlib and if you have multiple backends available to your matplotlib environment edit your matplotlibrc files as described in section 2 6 to select your default backend Selecting your default backend may be important especially if you intend to use matplotlib with an integrated development environment IDE This is described in the next section 2 3 Integrated development environments If you work primarily in an integrated development environment such as idle pycrust SciTE or Pythonwin you should set your default backend to be compatible with the GUI your IDE uses See Table 2 1 for a summary of the various python IDEs and their matplotlib compatibility IDE GUI Backends and Options idle Tkinter Works best with TkAgg if idle is launched with the n flag pycrust WX Works best with WX WXAgg pyshell GTK GTK GTKAgg Scintilla and SciTE GTK Should work with GTK GTKAgg backends but untested Eric3 Eric4 Qt Qt4 works with QtAgg Qt4Agg pythonwin MFC Unknown Table 2 1 python IDEs and matplotlib compatibility Tf you ha
69. nance array is one Typically you will not create a normalization instance yourself but may set vmin or vmax in the keyword argu ments of the image creation function In this case a normalization instance is created for you and your vmin vmax settings are applied If you do supply a normalization instance for the norm argument vmin and vmax will be ignored See Table 3 5 for some examples of image normalization commands and their interpretation command interpretation gt imshow X X lt min X 0 and X gt max X 1 gt imshow X vmax 10 X lt min X gt 0andX gt 10 1 gt imshow X vmin 0 vmax 10 X lt 0 0andX gt 10 1 gt anorm normalize 2 8 gt imshow X norm anorm X lt 2 gt 0adX gt 8 gt 1 Table 3 5 Example image normalization commands and their interpretation Once the luminance data are normalized they color mapper transforms the normalized data to RGBA using a matplotlib colors Colormap instance Common colormaps are defined in matplot1ib cm including cm jet and cm gray If the cmap argument to an image command is None the default is given by he rc parameter image cmap The keyword arguments cmap norm vmin vmax control color mapping and scaling in the image construction commands Once the images have been created several commands exist to interactively control the color map of the current image Like the current figure gcf and the current axes gca matplotlib keeps track of the current i
70. nd y data range and use these to update the data limits of the axes which is turn will be used to autoscale the view limits No drawing code is actually issued but is deferred until later 70 Line 3 show show is an interface to realize and show the GUI windows For image backends eg Agg PS or SVG it is superfluous The image backends will draw the figure on a call to savefig and ignore a show call Each GUI backend defines show to realize all of the GUI windows and start the GUI mainloop For this reason the call to show is blocking and should be the last line of the script Here is a representative show method from matplotlib backends backend_gtk def show mainloop True Show all the figures and enter the gtk main loop This should be the last line of your script for manager in Gcf get_all_fig_managers manager window show if gtk main_level 0 and mainloop if gtk pygtk_version gt 2 4 0 gtk main else gtk mainloop Typically the GUI backends binds the realize or expose event of the GUI window to ultimately trigger the Figure draw method of the Figure instance contained by the FigureCanvas In the show function above manager window show will trigger an expose event in pygtk The gtk backend binds the expose event to the FigureCanvasGTK expose_event method If the canvas has not yet been drawn the expose_event method will create a RendererGTK instance which derives from the common drawing API in
71. nds to the current axes and figure managing the interactive state and so on But that is all it does all of the plotting is handled by a set of classes that the user can instantiate directly If you are developing a GUI application or simply don t want any hidden magic in your plots you can create any plots using pure OO code that you could create with the pylab interface From a developer standpoint the pylab interface has been a blessing in disguise Because the interface was fixed by the Mathworks before the start of matplotlib provided considerable freedom to redesign the guts of the plotting library the object model can be totally revamped and the user interface remains fixed The matplotlib code is divided conceptually into 3 parts the MATLAB interface the matplotlib Artists and the backend renderers The pylab interface was covered in Chapter 3 This module pylab is comprised mainly of code to manage the multiple figure windows across backends and provide a thin procedural wrapper around the object oriented plotting code The matplotlib Artists are a series of classes that derive from matplotlib artist Artist so named because these are the objects that actually draw into the figure see Figure 8 3 The backend renderers each implement a common drawing interface that actually puts the ink on the paper eg creating a postscript document filling an antigrain pixel buffer or calling the gtk drawing code This chapter delves into matp
72. ng Any level is inclusive of all the levels below it If you setting is debug you 1l get all the debug and helpful messages When submitting problems to the mailing list please set verbose to helpful or debug and paste the output into your report The fileo gives the destination for any calls to verbose report These objects can a filename or a filehandle like sys stdout You can override the rc default verbosity from the command line by giving the flags verbose LEVEL where LEVEL is one of the legal levels eg verbose helpful H HH HHH HHH HH HH H 77 78 Appendix B mathtext symbols 79 80 Appendix C matplotlib source code license matplotlib is distributed under the Python Software Foundation PSF license which permits commercial and noncom mercial free use and redistribution as long as the conditions below are met The VERSION string below is replaced by the current matplotlib version number with each release LICENSE AGREEMENT FOR MAT 1 23 to rep deriva alone or ina License Agreement and 2002 2 matplo Licensee 3 This LICE Individual o matplotlib sof documentation Subject to hereby grants roduce analyze test perform and o tribute and otherwise use matplotlib VERSION rivative version provided however that JDH s JDH s notice of copy ter All Rights Reserved are retained in RSION alone or in any derivative version prepared by In the tive works
73. nipulate arrays When you import pylab you will get all of NumPy or Numeric or numarray depending on your numerix setting matplotlib is organized around figures and axes The figure contains an arbitrary number of axes which can be placed anywhere in the figure you want including over other axes You can directly create and manage your own figures and axes but if you don t matplotlib will try and do the right thing by automatically creating default figures and axes for you There are two ways of working in the pylab interface interactively or in script mode When working interactively you want every plotting command to update the figure Under the hood this means that the canvas is redrawn after every command that affects the figure When working in script mode this is inefficient In this case you only want the figure to be drawn once either to the GUI window or saved to a file To handle these two cases matplotlib has an interactive setting in matplotlibrc When interactive True the figure will be redrawn with each command When interactive False the figure will be drawn only when there is a call to show or savefig In the examples that follow Pll assume you have set interactive True in your matplotlibrc file and are working from an interactive python shell using a compatible backend Please make sure you have read and understood Sections 2 2 2 3 2 4 and 2 6 before trying these examples 3 1 Simple plots Just about the
74. not need to import any matplotlib names because in pylab mode ipython will import them for you ipython turns on interactive mode for you and also provides a run command so you can run matplotlib scripts from the matplotlib shell and then interactively update your figure ipython will turn off interactive mode during a run command for efficiency and then restore the interactive state at the end of the run gt gt gt cd python projects matplotlib examples home jdhunter python projects matplotlib examples gt gt gt run simple_plot py gt gt nie La new tattle Clor rl The pylab interface provides 4 commands that are useful for interactive control Note again that the interactive setting primarily controls whether the figure is redrawn with each plotting command isinteractive returns the interactive setting ion turns interactive on ioff turns it off and draw forces a redraw of the entire figure Thus when working with a big figure in which drawing is expensive you may want to turn matplotlib s interactive setting off temporarily to avoid the performance hit gt gt gt run mybigfatfigure py gt gt gt off turn updates off gt gt gt title now how much would you pay gt gt gt xticklabels fontsize 20 color green gt gt gt draw force a draw gt gt gt savefig alldone dpi 300 gt gt gt close gt gt gt ion turn updates back on gt gt gt plot rand 20 mfc g
75. nsAxes text right top right bottom horizontalalignment right verticalalignment bottom transform ax transAxes text right top right top horizontalalignment right verticalalignment top 31 transform ax transAxes ax text right bottom center top horizontalalignment center verticalalignment top transform ax transAxes ax text left 0 5 bottom top right center horizontalalignment right verticalalignment center rotation vertical transform ax transAxes ax text left 0 5 bottom top left center horizontalalignment left verticalalignment center rotation vertical transform ax transAxes ax text 0 5 left right 0 5 bottom top middle horizontalalignment center verticalalignment center transform ax transAxes ax text right 0 5 bottom top centered horizontalalignment center verticalalignment center rotation vertical transform ax transAxes ax text left top rotated nwith newlines horizontalalignment center verticalalignment center rotation 45 transform ax transAxes ais eo 3 6 4 mathtext matplotlib supports TEX mathematical expressions anywhere a text string can be used as long as the string is delimited by on both sides as in r 5 lambda embedded mathtext strings such as in r The
76. o draw_arc gc rgb 100 100 100 100 360 360 0 draw a dashed line gc set_dashes 0 5 10 gc set_joinstyle miter gc set_capstyle butt gc set_linewidth 3 0 broken with new API o draw_lines gc 50 100 150 200 250 400 100 300 200 250 draw some text using the matplotlib font manager prop FontProperties size 40 gc set_foreground b o draw_text gc 100 300 That s all folks prop 45 0 there is no standard renderer interface to save the input to a file Akas tlnis de ne ol Of tie Mene canvas liere 1 mas ne coll inav the figure canvas would make for the antigrain render o _renderer write_png figures renderer_agg png 8 1 2 The figure canvases 8 2 The matplotlib Artists 8 3 pylab interface internals Let s look at the simplest matplotlib script and walk through what happens under the hood This section will be of interest mainly to developers or those curious about matplotlib internals it can be safely skipped by others We ll assume you are using one of the GUI backends eg GTKAgg and have are running this as a script interactive False from pylab import plot 1 2 3 show 67 Inheritance diagram for backend FigureCanvases GUI backend N Base S Figure figure gt draw print_figure x Y DN MK FigureCanvas FigureCanvas Wx GTK a FigureCanvas FigureCanvas FigureCanvas FigureCanvas WXAgg FLTKAgg GTKAgg TkAgg
77. oolbars and event handling The RendererBase aka renderer handles all the drawing primitives in display coordinates typical renderer methods are draw_text and draw_lines The GraphicsContextBase aka textitgraphics context stores information about the graphics properties such as linewidth cap or join style color alpha translucency The FigureCanvasBase aka figure canvas is primarily a container class to hold the Figure instance this facilitates separation of the Figure from the backend dependent code For GUI backends the figure canvas should be a GUI widget embeddable in a GUI 65 window 8 1 1 The renderer and graphics context The renderer defines the low level matplotlib drawing API all of the drawing commands are done in display coordi nates The matplotlib Artist classes handle all of the layout and transformation issue and pass the primitive drawing commands on to the renderer The renderers know nothing about the matplotlib Artists and nothing about the pylab interface Their one and only job is to get ink onto the canvas The graphics context stores information about the objects to be drawn their color linewidths cap and join styles alpha transparency etc Taken together you can use the backend renderer and graphics context directly to make drawings This may not be advisable since the whole purpose of the matplotlib Artists and pylab interface is to simplify the process of getting ink onto the canvas but it is possible Ho
78. own in Listing 1 1 and the output in Figure 1 2 You can create a spectrogram with the specgram function specgram splits the data into NFFT length segments and plots the instantaneous power in each segment along the y axis using a pseudocolor plot unlike psd which averages the power across each segment 1000 15 800 15 600 30 45 400 60 75 200 90 o 105 0 5 10 15 Figure 3 12 A spectrogram generated by Listing 3 8 o Listing 3 8 Instantaneous power spectra with specgram see Figure 3 12 from pylab import 39 dt 0 0005 t arange 0 0 20 0 dt a 100 Hz signal sl sin 2 pixl00 t eredate samc aniste nite c hilt py 2 2100 1562 s2 2x sin 2x pix400 t mask where logical_and t gt 10 t lt 12 1 0 0 0 s2 s2 x mask add some noise into the mix nse 0 01 randn len t x sl s2 nse the signal NFFT 1024 the length of the windowing segments Fs int 1 0 dt the sampling frequency Pxx is the segments x freqs array of instantaneous power freqs is the frequency vector bins are the centers of the time bins in which the power is computed and im is the matplotlib image AxesImage instance Pxx freqs bins im specgram x NFFT NFFT Fs Fs noverlap 900 colorbar 3 11 Axes properties 3 12 Legends and tables 3 13 Navigation matplotlib comes with two navigation toolbars for the graphical user interfaces classic and toolbar2 You can use these to change th
79. pha transparency norm None the matplotlib colors normalization instance cmap None the matplotlib colors Colormap instance vmin None the min for image scaling vmax None the max for image scaling origin None the image origin The cmap norm vmin vmax and origin arguments are explained in the sections below pylab figimage is a thin wrapper of matplotlib figure figimage and you can generate figure images di rectly with the pythonic API using fig figimage X where fig is a Figure instance 3 7 3 Scaling and color mapping In addition to supporting raw image RGB and RGBA formats matplotlib will scale and map luminance data for MXN float luminance arrays The conversion from luminance data to RGBA occurs in two steps scaling and color mapping Mf you want a resampled image to occupy the full space of the figure canvas you can achieve this by specifying a custom axes that fills the figure canvas axes 0 1 0 1 and using imshow 36 Scaling is the process of normalizing an MxN floating point array to the 0 1 interval by mapping vmin to 0 0 and vmax to 1 0 where vmin and vmax are user defined parameters If either are None the min and max of the image data will be used respectively Scaling is handled by a matplotlib colors normalization instance which defaults to normalization vmin None vmax None ie the default is to scale the image so that the minimum of the luminance array is zero and the maximum of the lumi
80. plot t s subplot 212 subplot 212 psd s 512 1 dt psd s 512 1 dt The major differences are 1 NumPy has a function for creating arrays arange above whereas MATLAB has the handy notation 0 dt 10 2 Python uses square brackets rather than parentheses for array indexing and there are some small differences in how to do array lengths sizes and indexing But the differences are minute compared to the similarities 1 MATLAB and NumPy both do array processing and have a variety of functions that efficiently operate on arrays and scalars 2 moderately sophisticated signal processing white noise convolution power spectra is achieved in only a few lines of clear code and 3 plots are simple intuitive and attractive compare Figures 1 1 and Figures 1 2 0 15 0 10 0 05 0 00 0 05 Power Spectrum dB 0 10 20 30 40 50 Frequency Figure 1 2 Colored noise signal and power spectrum generated with python matplotlib as shown in Listing 1 1 Compare with MATLAB in Figure 1 1 Note that the wave forms are not identical because they were generated from random signals Hopefully this example will have instilled some confidence in those who have previously worked with MATLAB that migrating to Python is not too daunting a task However this guide will not attempt to serve as an introduction to Python itself and therefore assumes you already have a rudimentary knowledge of the language For users who are new to
81. provides a single FontManager that can be shared across backends and platforms The findfont method returns the best TrueType TTF font file in the local or system font path that matches the specified FontProperties The FontManager also handles Adobe Font Metrics AFM font files for use by the PostScript backend The design is based on the W3C Cascading Style Sheet Level 1 CSS1 font specification http www w3 org TR 1998 REC CSS2 19980512 Future versions may implement the Level 2 or 2 1 specifications The font family property has five values serif e g Times sans serif e g Helvetica cursive e g Zapf Chancery fantasy e g Western and monospace e g Courier Each of these font families has a default list of font names in decreasing order of priority associated with them You describe which family you want by choosing eg family serif and the font manager will search the font serif list looking for one of the named fonts on your system The lists are user configurable and reside in your matplotlibrc This allows you to choose your family in your matplotlib script and the font manager will try and find the best font no matter which platform you run on The font style property has three values normal or roman italic or oblique The oblique style will be used for italic if it is not present The font variant property has two values normal or small caps For TrueType fonts which are scal
82. r a python plotting package I had several requirements BTM e Plots should look great publication quality One important requirement for me is that the text looks good antialiased etc e Postscript output for inclusion with TX documents e Embeddable in a graphical user interface for application development e Code should be easy enough that I can understand it and extend it e Making plots should be easy Finding no package that suited me just right I did what any self respecting python programmer would do rolled up my sleeves and dived in Not having any real experience with computer graphics I decided to emulate MATLAB s plotting capabilities because that is something MATLAB does very well This had an added advantage many people have a lot of MATLAB experience and thus they can quickly get up to steam plotting in python From a developer s perspective having a fixed MATLAB inspired user interface the pylab interface has been very useful because the guts of the code base can be redesigned without affecting user code The matplotlib code is conceptually divided into three parts the pylab interface is the set of functions provided by matplotlib pylab which allow the user to create plots with code quite similar to MATLAB figure generating code The matplotlib frontend or matplotlib API is the set of classes that do the heavy lifting creating and managing figures text lines plots and so on This is an abstract
83. rix array see Recipe 7 4 1 The following examples will assume you have your image data loaded into a numerix array either luminance MxN RGB MxNx3 or RGBA MxNx4 3 7 1 Axes images An axes image is created with im imshow X where X is a numerix array an imis a matplotlib image AxesImage instance The image is rescaled to fit into the current axes box Here is some example code to display an image create a random MxN numerix array and plot it as an axes image 34 from pylab import X rand 20 20 im imshow X imshow a command in the pylab interface This is a thin wrapper of the matplotlib Axes imshow method which can be called from any Axes instance eg ax imshow X There are two parameters that determine how the image is resampled into the axes bounding box interpolation and aspect The following interpolation schemes are available bicubic bilinear blackman100 blackman256 black man64 nearest sinc144 sinc256 sinc64 splinel6 and spline36 The default interpolation method is given by the value of image interpolation in your matplotlibrc file aspect can be either equal auto or some number which will constrain the aspect ratio of the image The default aspect setting is given by the value of the rc parameter image aspect The full syntax of the imshow command is imshow X the cmap None the norm None the aspect None the interpolation None the alpha 1 0 the vmin None the v
84. rmat the y axis in dollars ax yaxis set_major_formatter dollarFmt call autoscale to pick intelligent view limits based on our major tick locator ax autoscale_view rotate the x labels for nicer viewing labels ax get_xticklabels setp labels rotation 45 fontsize 10 grid True 55 56 Chapter 7 Cookbook 7 1 Plot elements 7 1 1 Horizontal or vertical lines spans It is often useful to draw a line that stretches from the left to the right side of the axes at a given height eg to represent a y axis threshold In this case the left and right are plotted in axes coordinates 0 and 1 respectively and the y coordinate is in data coordinates Plotted this way the horizontal extent of the line will not change if you interactively change the xlimits eg by using the pan navigation tool Although you can create these lines yourself using matplotlib lines Line2D instances and setting the appropriate transforms several helper functions are provided to make this easier 7 1 2 Fill the area between two curves The fill command takes a list of vertices and draws a polygon A filled area between two curves is simply a large polygon All you need to do is get the vertices in the correct order which basically means reversing the order of the x y pairs in one of the lines so that path across the vertices of the polygon is continuous Here is a simple example Listing 7 1 Fill the area between two curves see Figur
85. s Thus you can call and Axes or Subplot method on it When creating multiple subplots with the same axes for example the same time axes sometimes it helps to turn off the x tick labeling for all but the lowest plot Here is some example code subplot 211 plot 1 2 3 1 2 3 set gca xticklabels subplot 212 plot 1 2 3 1 4 9 Likewise with multiple columns and shared y axes you may want turn off the ytick labels for all but the first row The subplot command returns a matplotlib axes Subplot instance which is derived from matplotlib axes Axes Thus you can call and Axes or Subplot method on it Subplot defines some helper methods is_first_row is_first_col is_last_row is_last_col to help you conditionally set subplot properties eg 0 i in range numRows for j in range numCols ent 1 ax subplot numRows numCols cnt plot blah blah if ax is_last_row xlabel time s if ax is_first_col ylabel volts Here is some example code to create multiple figures and axes using the figure and subplot command to control the current figure and axes from pylab import t arange 0 0 2 0 0 01 sl sin 2 pixt s2 sin 4xpixt figure 1 subplot 211 plot t sl subplot 212 plot t 2xs1 figure 2 plot t s2 now switch back to figure 1 and make some changes to the upper subplot figure 1 subplot 211 plot t s2 gs set gca xticklabels show
86. sers will choose one option and make this setting in their rc file using either numerix Numeric numerix numarray ornumerix numpy see Section 2 6 2 6 Customization using matplotlibre Almost all of the matplotlib settings and figure properties can be customized with a plain text file matplotlibrc This file is installed with the rest of the matplotlib data fonts icons etc into a directory determined by python s installation module Before compiling matplotlib matplotlibrc resides in the same dir as setup py and will be copied into your install path Typical locations for this file are C Python24 Lib site packages matplotlib mpl data matplotlibrc windows usr lib python2 4 site packages matplotlib mpl data matplotlibrc linux and friends By default the installer will overwrite the existing file in the install path so if you want to preserve your changes please move it to the matplotlib directory in your HOME directory and set the HOME environment variable if necessary In the rc file you can set your backend Section 2 2 your numerix setting Section 2 5 whether you ll be working interactively Section 2 4 and default values for most of the figure properties 2 6 1 RC file format Blank lines or lines starting with a comment symbol are ignored as are trailing comments Other lines must have the format key val optional comment where key is some property like backend lines linewidth or figure figsize and
87. simplest plot you can create is gt gt gt from pylab import x gt gt gt plot 1 2 3 I have set my backend to backend TkAgg which causes the plot in Figure 2 1 to appear with navigation controls for interactive panning and zooming I can continue to decorate the plot with labels and titles gt gt gt xlabel time s gt gt gt ylabel volts gt gt gt title A really simple plot gt gt gt grid True 17 ve ANE Areally simple plot 3 25 2 15 1 0 0 5 Y 15 2 time s L Ses ea a a volts Figure 3 1 A simple plot decorated with some text labels and an axes grid and the updated figure is shown in Figure 3 1 At this point we re getting a little bored plotting 1 2 3 matplotlib is designed around plotting numerix arrays and can handle large arrays efficiently To create a regularly sampled 1 Hz sine wave use the arange and sin methods methods provided by numerix which produces the plot shown in Figure 3 2 gt gt gt t arange 0 0 3 0 0 05 in matlab t 0 0 0 05 3 0 gt gt gt s sin 2 pixt gt gt gt plot t s E Figure 1 SAA A really simple plot 3 e 0 05 1 15 2 25 3 time s L ss ANSIA F Figure 3 2 A sine wave added to the simple plot This may not be what we wanted Because the hold state was on the two plots were superimposed Note that the two plots are superimposed matplotlib and MATLAB have a hold
88. the event handler def clickl event pass def click2 event pass cidl connect key_press_event click1 cid2 connect key_press_event click2 42 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 Table 3 6 The event attributes coo later OM ooo disconnect cidl now only click2 is connected Here s an example to get the mouse location in data coordinates as the mouse moves Connect to the mouse move event and print the location of the mouse in data coordinates if the mouse is over an axes from pylab import plot arange 10 def on_move event get the x and y pixel coords Mo Y event x GVON if event inaxes print data coords event xdata event ydata connect motion_notify_event on_move show 3 15 Customizing plot defaults 43 Chapter 4 Font finding and properties matplotlib fonts font_manager is module for finding managing and using fonts across platforms This module
89. the matplot1ib numerix module written by Todd Miller allows you to choose between Numeric numarray and NumPy at the prompt or in a config file Thus when you do import matplotlib and all the numerix functions from pylab import you ll not only get all the matplotlib pylab interface commands but most of the Numeric numarray or NumPy package as well depending on your numerix setting All of the array creation and manipulation functions are imported such as array arange take where etc The other modules such as mlab fft and linear_algebra are available under the numarray package structure To make your matplotlib scripts as portable as possible with respect to your choice of array packages it is advised not to explicitly import Numeric numarray or NumPy Rather you should use matplotlib numerix where possible either by using the functions imported by pylab or by explicitly importing the numerix module as in create a numerix namespace import matplotlib numerix as n x n arange 100 y n take x range 10 20 For the remainder of this manual the term numerix is used to mean either the Numeric numarray or NumPy package 2 5 1 Choosing Numeric numarray or NumPy To select Numeric numarray or NumPy from the prompt run your matplotlib seript with 14 gt python myscript py numarray use numarray gt python myscript py Numeric use Numeric gt python myscript py numpy use NumPy Typically however u
90. ther to use numeric to clip data label A string optionally used for legend linestyle Oneof linewidth A float the line width in points marker Oneof 0o0 svx gt lt etc 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 Table 3 1 Line properties see pylab plot for more marker styles Using keyword arguments to control line properties You can set any of the line properties listed in Table 3 1 using keyword arguments to the plot command The following command plots large green diamonds with a red border gt gt gt plot t sl markersize 15 marker d markerfacecolor g markeredgecolor r Using set to control line properties You can set any of the line properties listed in Table 3 1 using the set command Set operates on the return value of the plot command a list of lines so you need to save the lines You can use an arbitrary number of key value pairs gt gt gt lines plot t sl gt gt gt set lines markersize 15 marker d markerfacecolor g markeredgecolor r set can either operate on a single instance or a sequence of instances in the example code above lines is a length one sequence of lines Under the hood if you pass a keyword arg named something set looks for a method of the object called set_something and will call
91. ts a large number of TEX math symbols and commands to support mathematical expressions anywhere in your figure To get the most out of text in matplotlib you should use a backend that supports freetype2 and mathtext notably all the Agg backends see Section 2 2 or the postscript backend which embeds the freetype fonts directly into the PS EPS output file 3 6 1 Basic text commands The following commands are used to create text in the pylab interface e xlabel s add a label s to the x axis ylabel s add a label s to the y axis title s add a title s to the axes e text x y s add text s to the axes at x y in data coords figtext x y s add text to the figure at x y in relative 0 1 figure coords 3 6 2 Text properties The text properties are listed in Table 3 4 As with lines there are three ways to set text properties using keyword arguments to a text command calling set on a text instance or a sequence of text instances or calling an instance method on a text instance These three are illustrated below keyword args gt gt gt xlabel time S color r size 16 gt gt gt title Fun with text horizontalalignment left use set gt gt gt locs labels xticks gt gt gt set labels color g rotation 45 29 instance methods gt gt gt 1 ylabel volts gt gt gt l set_weight bold Property Value alpha The alpha transparency on
92. tter class has access to the axis view and data limits To control the major and minor tick label formats use one of the following methods ax ax ax ax xaxis xaxis set_minor_formatter xminorFormatter yaxis yaxis set_major_formatter xmajorFormatter set_major_formatter ymajorFormatter set_minor_formatter yminorFormatter SS OS 6 3 Example 1 major and minor ticks In this example the xaxis has major ticks that are multiples of 20 and minor ticks that are multiples of 5 The ticks are formatted with an integer format string formatter d The minor ticks are unlabelled NullFormatter The MultipleLocator ticker class is used to place ticks on multiples of some base The Format StrFormatter uses a string format string eg d or 1 2f or 1 1f cm to format the tick 52 Note that the pylab interface grid command changes the grid settings of the major ticks of the y and y axis to gether If you want to control the grid of the minor ticks for a given axis use for example ax xaxis grid True which minor See Figure 6 1 1 0 0 5 0 0 0 5 Figure 6 1 Creating custom major and minor tick locators and formatters see List ing 6 1 Listing 6 1 Custom tickers and formatters see Figure 6 1 from pylab import import the tick locator and formatter classes from matplotlib ticker import MultipleLocator FormatStrFormatter majorLocator MultipleLocator 20 multiples of 20
93. type is listed below in upper case If the attribute is a sequence for example the figure contains a list of Axes then the connecting edge is labeled 0 and the object type is in square brackets to indicate a list eg Axes Some redundant information is omitted for example the yaxis contains the equivalent objects that the xaxis contains the minorTicks have the same containment hierarchy as the majorTicks and so on axes which in turn are interfaces to the Gcf class that does the real lifting Line 2 plot 1 2 3 All of the pylab functions are defined similarly they get the current axes and forward the call on to the corresponding matplotlib axes Axes method which does the real work The plot command in the example below calls gca to get the current axes If no figure or axes has been defined at the time of this call the are created one on the fly using default parameters from the rc file ultimately the new_figure_manager backend method is called to provide new figures when needed and the default subplot 111 is added to the figure if no other axes has been defined The new_figure_manager method deserves a bit more attention because this creates the central object that con tains all the other objects relevant to the creation of a single figure matplotlib backend_bases FigureManagerBase 1s a container class for the figure window a GUI window and figure canvas a GUI widget which can be drawn upon The figure canvas derives from m
94. ur programs with pythonw rather than python or you may get nonresponsive GUIs 10 2 1 4 Trial Run To test your matplotlib installation run Python in pylab mode which includes special support for interactive use of matplotlib Linux and Mac users run the following in a shell ipython pylab Windows users can edit the ipython launch icon properties to include the pylab flag IPython s pylab mode automatically imports matplotlib and prepares the session for interactive plotting At the command prompt In 1 run the following plot 1 2 3 A window should appear which looks like figure 2 1 If you get errors instead of a plot window you probably were missing one of the packages required by matplotlib during installation Now that we have hopefully demonstrated how easy it can be to get started perhaps it is safe to explore the various options associated with installing and configuring matplotlib E es ee al E Figure 2 1 A simple plot shown in the TkAgg graphical user interface Navigation controls shown below the figure provide an easy way to pan and zoom around your figures and a save dialog allows you to save your figure after you have set the pan and zoom 2 2 Backends The matplotlib backends are responsible for taking the figure representation and transferring this to a display device either a hardcopy image jpg png ps svg etc or a GUI window that you can interact with
95. urce code license 81 Chapter 1 Introduction matplotlib is a library for making 2D plots of arrays in python Although it has its origins in emulating the MATLAB graphics commands it does not require MATLAB and can be used in a pythonic object oriented way Although matplotlib is written primarily in pure python it makes heavy use of NumPy and other extension code to provide good performance even for large arrays matplotlib is designed with the philosophy that you should be able to create simple plots with just a few commands or just one If you want to see a histogram of your data you shouldn t need to instantiate objects call methods set properties and so forth it should just work For years I used to use MATLAB exclusively for data analysis and visualization MATLA excels at making it easy to create nice looking plots When I began working with EEG data I found that I needed to write applications to interact with my data and developed an EEG analysis application in MATLAB As the application grew in complexity interacting with databases http servers manipulating complex data structures I began to strain against the limitations of MATLAB as a programming language and decided to start over in python python more than makes up for all of matlab s deficiencies as a programming language but I was having difficulty finding a 2D plotting package for 3D VTK more than exceeds all of my needs When I went searching fo
96. val is the value of that property Example entries for these properties are this is a comment and is ignored backend GTKAgg the default backend lines linewidth OS line width in points figure figsize 2 83 figure size in inches A complete sample rc file is shown in Appendix A The matplotlib re values are read into a dictionary rcParams which contains the key value pairs You can changes these values within a script by importing this dictionary For example to require that a given script uses numarray you could do from matplotlib import rcParams rcParams numerix numarray from pylab import Additionally the matplotlib rcParams dictionary and matplotlib rcdefaults can be used to dynamically cus tomize the defaults during a script execution 2 6 2 Which rc file is used matplotlib will search for an rc file in the following locations e The current directory this allows you to have a project specific configuration that differs from your default configuration 15 e Your HOME dir On linux and other UNIX operating systems this environment variable is set by default Windows users can set in the My Computer properties e PATH matplotlibrc where PATH is the return value of matplotlib get_data_path This function looks where distutils would have installed the file if it doesn t find it there it checks for the environment variable MATPLOTLIBDATA and uses that if found The latter should be set if you
97. ve experience with these or other IDEs and matplotlib backends to help me finish this table please contact me or the matplotlib devel mailing list 12 2 4 Interactive The recommended way to use matplotlib interactively from a shell is with IPython IPython has a pylab mode launched with ipython pylab that detects your matplotlibre file and makes the right settings to run matplotlib with your GUI of choice in interactive mode using threading Ipython s pylab mode is compatible with the Tk GTK WX and Qt GUI toolkits GTK users will need to make sure that they have compiled GTK with threading for this to work Using ipython in pylab mode is basically a nobrainer because it knows enough about matplotlib internals to make all the right settings for you peds pc311 gt ipython pylab Python 2 3 3 2 Apr 13 2004 17 41 29 Type copyright credits or license for more information IPython 0 6 5 An enhanced Interactive Python Y gt Introduction to IPython s features magic gt Information about IPython s magic functions help gt Python s own help system object gt Details about object object also works prints more Welcome to pylab a matplotlib based Python environment help matplotlib gt generic matplotlib information help matlab gt matlab compatible commands from matplotlib help plotting gt plotting commands mile plori amd 20 wamel 20 7807 Note that you did
98. wever it is potentially useful to developers who may want to extend the capabilities of matplotlib eg to implement block diagram drawing Every backend in matplotlib backends defines a Renderer that inherits from RendererBase some also define a backend dependent GraphicsContext while other simply use the GraphicsContextBase for storing the informa tion and do all the work of translating these values in the Renderer This is the approach the Agg backend uses shown in the listing below Ox 9 N x Figure 8 1 Drawing directly with the backend renderer and graphics context see List ing 8 1 Listing 8 1 Drawing with the agg renderer see Figure 8 1 working directly with renderer and graphics contexts primitives from matplotlib font_manager import FontProperties from matplotlib backends backend_agg import RendererAgg from matplotlib transforms import Value a 400x400 canvas at 72dpi canvas dpi Value 72 0 o RendererAgg 400 400 dpi the graphics context 66 gc 0 new_gc draw the background white gc set_foreground w face 1 1 1 white o draw_rectangle gc face 0 0 400 400 the gc s know about color strings and can handle any matplotlib color arguments hex strings rgb format strings etc gc set_foreground g gc set_linewidth 4 face 1 0 0 must be rgb o draw_rectangle gc face 10 50 100 200 draw a translucent ellipse rgb 0 0 1 gc set_alpha 0 5
99. y data in python and saving the results to data files for plotting in MATLAB When that became too cumbersome I decided to write matplotlib so I could have all the functionality I needed in one environment Here is a brief example show ing how to iterate over several data files named basename001 dat basename002 dat basename003 dat basenamel00 dat and plot all of the traces to the same axes T ll assume for this example that each file is a 1D ASCII array which I can load with the load command hold True set the hold state to be on for i in range 1 101 start at 1 end at 100 fname basename 03d dat i 03d pads the integers with zeros x load fname plot x 3 5 axes and figures All the examples thus far used implicit figure and axes creation You can use the functions figure subplot and axes to explicitly control this process Let s take a look at what happens under the hood when you issue the commands gt gt gt from pylab import x gt gt gt plot 1 2 3 When plot is called the pylab interface makes a call to gca get current axes to get a reference to the current axes gca in turn makes a call to gc to get a reference to the current figure gcf finding that no figure has been created creates the default figure figure and returns it gca will then return the current axes of that figure if it exists or create the default axes subplot 111 ifit does not Thus the code above is equivalent to
Download Pdf Manuals
Related Search
Related Contents
SC100 Load Cell And Edge Guide Amplifier 21163 Connector Cover - CIVCO Medical Solutions 取扱説明書 - LIXIL Origin Storage 1TB MLC SATA 2.5" Samsung GT-E1100T คู่มือการใช้งาน Hand - Rührgerät Handheldagitator Asrock FM2A78M Pro4+ Casio 5235 Watch User Manual EARTH GROUND TESTER COMPROBADOR DE Copyright © All rights reserved.
Failed to retrieve file