FAQs = ( ('FAILURE', "matplotlib compiled fine, but I can't get anything to plot" , """\ The first thing to try is to remove site-packages/matplotlib and reinstall. If you are running the windows installer or using some other package, that is all you need to do. If you are compiling matplotlib yourself, you also need to remove the build subdirectory of the matplotlib src tree you are compiling from. It is not enough to do python setup.py clean. Try rebuilding and reinstalling matplotlib after removing these two directories and see if that helps. If not, read on.
The best way to test your install is by running a script, not working interactively from a python shell or an integrated development environment such as IDLE. Each of those brings additional complexities, as described at interactive matplotlib and this faq. So open up a UNIX shell (or a DOS command prompt) and cd into a directory containing a minimal example in a file. Something like simple_plot.py or just this
from pylab import * plot([1,2,3]) show()and run it with (the verbose flag below is for matplotlib-0.64 or later)
> python simple_plot.py --verbose-helpfulThis will give you additional information about which backends matplotlib is loading, version information, and more. At this point you might want to make sure you understand matplotlib's configuration process, governed by the configuration file matplotlibrc which contains instructions within and the concept of the matplotlib backend.
If you are still having trouble, please post a question and the output of --verbose-helpful to the mailing list. """), ('PYGTK24', "I can't compile matplotlib with pygtk 2.4." , """\ This is a pygtk bug. The patch is in pygtk CVS. You basically need to add the G_BEGIN_DECLS/G_END_DECLS macros, and rename typename parameter to typename_
- const char *typename, + const char *typename_,"""), ('ZORDER', "How can I control the order that my plot elements appear" , """\ Within an axes, the order that the various lines, markers, text, collections, etc appear is determined by the zorder property (matplotlib-0.65 or later). The default order is patches, lines, text, with collections of lines and collections of patches appearing at the same level as regular lines and patches, respectively. See examples/zorder_demo.py. """), ('TOOLBAR2', 'Nothing happens when I click the new toolbar buttons', """\ The Home, Forward and back buttons on the new toolbar are used to navigate between previously defined views. If you haven't navigated anywhere, these buttons will have no effect. The Pan/Zoom, and zoom to rect buttons activate a navigation mode, but by themselves do nothing. After clicking one of them, you need to put your mouse over and axes and click/drag. Then the navigation tools take effect - see the toolbar2 tutorial. """), ('LOG', "I'm getting a log of zero error even though I know all of my data are positive", """\ This is definitely a gotcha that matplotlib needs to be smarter about. The log zero error is occurring when the transformation is made on the axes limits and not on the data. The autoscaler picks the best min/max for the data coordinates, and will round down or up to facilitate nice integer ticking. When you plot with linear coords, the autoscaler makes its pick according to linear scaling, and if when you change scales the old scaling is in effect and the log transform fails when converting the viewport. Solution: rescale the axes after changing coords, either manually
ax.set_yscale("log") ax.set_xscale("log") axis([minx, maxx, miny, maxy])or use the autoscaler
ax.set_yscale("log") ax.set_xscale("log") ax.autoscale_view()or set your log coords *before* calling a plot command
ax = gca() ax.set_yscale("log") ax.set_xscale("log") errorbar(x,y,err,fmt='o')and then the errorbar command will pick a "locator" to handle ticking and viewport scaling appropriately from the outset. This is the approach taken in log_bar.py. """), ('FREEZE', 'My matplotlib window is freezing', """ Often times this is caused by running matplotlib with a backend that is not compatible with your shell or IDE.
There are known incompatiblities with some of the backends with some of the IDEs, because they use different GUI event handlers. If you want to use matplotlib from an IDE, please consult the backends documentation for compatibility information. You will have the greatest likelihood of success if you run the examples from the command shell or by double clicking on them, rather than from an IDE.
If you are trying to generate plots interactively from the shell, you need a shell that is compatible with your backend. Currently, your best bet is TkAgg from the standard python shell or ipython. There are a couple of custom GTK shells you can use, described here.
To find out which IDEs are compatible with your backend, see backend.
To test whether you are experiencing a problem inherent in matplotlib, you should open up a command shell and try to run one of the examples from the matplotlib src distribution (the *.zip file for windows users); Eg,
c:\matplotlib\examples> python simple_plot.pyIf this works fine, then you likely have an IDE/shell problem and not a matplotlib specific problem. Unfortunately, this problem tends to crop up a lot. See for example this thread and the responses to that post for more information. """), ('MOVIE', 'How do I make a movie with matplotlib?', """\ If you want to take an animated plot and turn it into a movie, the best approach is to save a series of image files (eg PNG) and use an external tool to convert them to a movie. There is a matplotlib tutorial on this subject here. You can use mencoder, which is part of the mplayer suite for this
#fps (frames per second) controls the play speed mencoder 'mf://*.png' -mf type=png:fps=10 -ovc \\ lavc -lavcopts vcodec=wmv2 -oac copy -o animation.aviThe swiss army knife of image tools, ImageMagick's convert, works for this as well Here is a simple example script that saves some PNGs, makes them into a movie, and then cleans up.
import os, sys from pylab import * files = [] figure(figsize=(5,5)) ax = subplot(111) for i in range(50): # 50 frames cla() imshow(rand(5,5), interpolation='nearest') fname = '_tmp%03d.png'%i print 'Saving frame', fname savefig(fname) files.append(fname) print 'Making movie animation.mpg - this make take a while' os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=10 \\ -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o animation.mpg") # cleanup for fname in files: os.remove(fname)"""), ('WRONGDIR', "When I try to import pylab, I get an error about no _transform.so or ft2font.so", """ If you are trying to run matplotlib from the matplotlib build dir, you will fail. This is because the matplotlib python src dir is in your module path, but it does not include the compiled extension modules which are in site-packages/matplotlib. Change into another directory and try again.
If the problem persists, see if the required object files are in site-packages/matplotlib. If not, something is wrong with your install. You may want to try rebuilding with
> rm -rf build > python setup.py build > build.outand post the results to the matplotlib-devel or matplotlib-users mailing lists. """), ('EXAMPLES', 'Where can I find information about what matplotlib can do?', """\ There are a lot of features under the hood in matplotlib. This tutorial is a good place to start. When you are finished with it, the next step (other than getting to work on your own figures, of course) is to download the source distribution and take a look at the examples subdirectory. If you are working with date plots you'll find several date demos with obvious filenames like examples/date_demo1.py. Likewise, you'll find examples for images (examples/image_demo.py), contouring (examples/contour_demo.py, using matplotlib with a graphical user interface (examples/embedding_in_wx.py and many more. At last count, there were 116 examples. Because these are not included with the standard windows installer, they are often overlooked, which is why I emphasize them here.
The next place to turn to find the hidden gems is the what's new page. Every feature ever introduced into matplotlib is listed on that page with the version it was introduced, usually with links to examples and functions. Scrolling through that page is one of the best ways to find out what capabilities and customizations are supported.
"""), ('LARGEPS', "My PS/EPS files are huge; what's wrong?", """ With matplotlib-0.61, Paul Barrett introduced truetype fonts in backend_ps, primarily in order to support mathtext. Because he was unable to get the individual glyphs from freetype, he had to dump the entire font into the PS file. A typical font takes about 300K of noncompressed space. This, however, is a fixed cost and does not increase with the complexity of the figure or number of points plotted. It would, however, increase if you use multiple fonts, eg in mathtext.
Before 0.61, we used the afm fonts that ship with matplotlib and matplotlib has its own AFM parser which handles character metrics, kerning, etc. It would not be too much work to have an option (eg in the matplotlib rc file) which allows users to simply use AFM fonts when possible (eg when not using mathtext) in which case you wouldn't see these big eps files. The other advantage to this approach is that they seem to render nicer in some viewers, eg xdvi.
One nice thing about dumping the truetype into the ps files is that the text is the same across backends. The ideal solution would be able to dump just the glyphs needed, which presumably would be much smaller, but we haven't figured this out yet.
Given that the 300K is a fixed cost (118K gzipped), if you still find the size sufficiently troublesome that it justifies the extra work (on our end) to provide an option to revert to AFM fonts, please let us know on the mailing list. """), ('PROMPT', "After my matplotlib script runs, I get a python shell prompt. What's going on?", """ Tkinter, used by the default windows backend TkAgg not have a mainloop like GTK or WX. We needed a way to keep the figure open, and decided the best way was to switch into interactive mode in python. This has the additional benefit that you can issue additional python commands to customize your figure interactively, if you want. """), ('USE', "matplotlib seems to be ignoring the use command", """ You must use the use command before importing pylab, as described on backends
>>> import matplotlib >>> matplotlib.use('Agg') >>> from pylab import *Note that if you are using an IDE like pycrust, pythonwin, or IDLE, pylab may have already been loaded, and subsequent calls to use or from pylab import * will have no effect unless you explicitly force a module reload. """), ('VERSIONS', 'What do the version numbers mean?', """ The system has been evolving a bit, but here is what I am currently using
Some of the matplotlib extension code operates on Numeric/numarray arrays, eg the image and transforms modules. To get optimum performance, you need to compile matplotlib with the package you want to use. matplotlib setup.py will automatically detect whether you have Numeric or numarray or both at compile time, and will compile the appropriate extensions to work with one or both, if present. The actual extension chosen at runtime will be determined by your 'numerix' matplotlibrc setting."""), ('SLOW', 'matplotlib seems painfully slow, am I doing something wrong?', """\ Hopefully, yes. A lot of work has gone into making matplotlib reasonably fast plotting largish arrays and image data. If things seem exceptionally pokey, it may indicate a problem in your setup. Before matplotlib-0.64, the most common cause is getting your numerix settings out of kilter. As indicated in the numarray faq, it is important that the Numeric/numarray extension you want to use is available at the time you compile matplotlib, since the appropriate extensions are determined automatically when matplotlib is compiled. Both Numeric and numarray extensions are available in the windows installer . Failure to do so can cause up to a 30-fold performance hit in some cases.
Also, if you are running a python script, make sure your interactive setting in your .matplotlirc is false; otherwise the figure will be redrawn with every plotting command when what you want if for the figure to be drawn only once at the end of the script. See interactive and what's up with show? for more information.
For images, matplotlib-0.70 added a number of optimizations that delivered approximately a 4x performance boost over earlier versions. So if you need fast image support, make sure you are using the latest release. Also, the matplotlib normalization code, which converts image data on an arbitrary scale to the unit interval, may be unnecessary if your data is already scaled to the unit interval. You can avoid this cose by writing a do-nothing normalization function.
class mynorm(normalize): def __call__(self, X): return X imshow(X, norm=mynorm())Another possibility to speed things up is to use collections, which were designed to efficiently plot large numbers of objects with some shared properties. If you find youself issuing many spearate plot commands, or instantiating many Line2D or Patch objects, you may benefit from recoding with collections. See the matplotlib.axes.Axes implementatation of scatter and pcolor, and the matplotlib.finance module, for examples.
If you are experiencing problems with performance, please post an example to the mailing list. It would be helpful to provide as much information as possible, such as what OS you are on, what backend you are using, the size of the data arrays you are plotting, and the output of python yourscript.py --verbose-helpful. """), ('MATPLOTLIBRC', 'How do I customize the default behavior of matplotib?', """ Recent versions of matplotlib (0.51 or later) use a configuration file to set everything from the default font, to the figure size, to the default line width. See .matplotlibrc for a sample config file and information on how to use it. """), ('OO', 'Is there any guide to using matplotlib with pythonic / OO /API rather than the pylab interface?', """ There is no official documentation yet, but there are a few resources
from distutils.core import setup import glob import py2exe data = glob.glob(r'C:\Python23\share\matplotlib\*') data.append(r'C:\Python23\share\matplotlib\.matplotlibrc') setup( console = ["simple_plot.py"], data_files = [("matplotlibdata", data)], )You don't need anything special in your plotting script. Eg, the following works fine with recent versions of py2exe
from pylab import * plot([1,2,3]) show()matplotlib should be able to find your matplotlib data directory. You can still configure the defaults in dist/matplotlibdata/.matplotlibrc after the application has been frozen.
Note you may get warnings like "The following modules appear to be missing" but in general I have found these to be harmless for freezing matplotlib.
To freeze GTK or GTKAgg, you need to do a couple of extra things, including creating a setup.cfg file and copying the lib and etc subdirectories of yout GTK install tree to your py2exe dist subdir. See the simple_plot_gtk subdirectory in the py2exe examples zip file.
If you want to reduce the size of your application by excluding certain backends, see the matplotlib py2exe wiki entry. """), ('CUSTOM', 'How do I dynamically change the rc defaults?', r""" If you want to customize a session of matplotlib, eg, the default font, linewidth, fontsize, etc, use the rc command. This changes the default for the rest of the session, or until you issue another rc command. See customize_rc.py for example usage."""), ('GTKPATH', 'I cannot import gtk / gdk / gobject', """ Basically, there are 3 things that I've seen cause failure (relative likelihood in parentheses):
For publication submission or use with TeX, however, the postscript backend is naturally a good choice.
figure(figsize=(6,4)) plot(blah, blah) savefig('myfile', dpi=75)See ttf fonts for more information. """ ), ('SHOW', "What's up with 'show'? Do I have to use it?", """ You do not need this function with the image backends (Agg, Cairo, Paint, GD, PS) but you do need it with the GUI (GTK, WX, TkAgg, GTKAgg, GTKCairo) backends, unless you are running matplotlib in interactive mode.
Because it is expensive to draw, I want to avoid redrawing the figure many times in a batch script such as the following
plot([1,2,3]) # draw here ? xlabel('time') # and here ? ylabel('volts') # and here ? title('a simple plot') # and here ? show()It is possible to force matplotlib to draw after every command, which is what you want in interactive mode, but in a script you want to defer all drawing until the script has executed. This is especially important for complex figures that take some time to draw. 'show' is designed to tell matplotlib that you're all done issuing commands and you want to draw the figure now. In the TkAgg backend, which can be used from an arbitrary python shell interactively, it also sets interactive mode. So you can launch your script with python -i myscript.py -dTkAgg and then change it interactively from the shell. IMPORTANT: show should called at most once per script and it should be the last line of your script. At that point, the GUI takes control of the interpreter. If you want to force a figure draw, use draw instead. """), ('PSGUI', 'Can I save PS/EPS from a GUI backend?', """ Yep. Just choose a filename that contains ps in the extension, eg somefile.ps or somefile.eps and matplotlib will try and do the right thing. That is, if it's an eps file, it will include a bounding box, if it's a ps file it will output plain postscript. It is recommended you use matplotlib-0.50 or later for this feature to work properly."""), ('TEXTOVERLAP', 'My title or ticklabel or whatever is overlapping some other figure element, what should I do?', """ The default subplots take up a lot of room. If you need extra space for particularly large labels and titles, consider using custom axes, eg, axes([0.3, 0.3, 0.6, 0.6]) gives you more room to the left and at the bottom than the standard axes. Other things to consider. With multiple subplots, eg, multiple rows, turn off the xticklabels for all but the lowest subplot if they are the same in all subplots set(gca(), 'xticklabels', []). You can make the fontsizes smaller, as in xlabel('time (s)', fontsize=8) or, for the tick labels
t = gca().get_xticklabels() set(t, 'fontsize', 8)You can also set the default ticklabel size in your matplotlibrc file or override it for a single plot using rcParams."""), ('DYNAMIC', 'Can matplotlib do dynamic plots, like digital oscilloscopes or animations?', """ Absolutely. See for example, anim.py and system_monitor.py"""), ('AXES', 'Can I change the size of the subplots', """ subplot is just a helper function to generate regularly spaced axes. For more fine-grained control, you can position axes anywhere you want in any size using the axes command. See the axes command and the example axes_demo.py.
"""), ('IMAGES', 'Can matplotlib handle image data?', """ Yes - you can now plot images from numerix arraysq with imshow. You can load png files into arrays imread; image loaders coming soon."""), ('ROTATETICKS', 'How do I make vertical xticklabels?', """ You can set the rotation of any text instance to vertical
from pylab import * plot([1,2,3,4], [1,4,9,16]) set(gca(), 'xticks', [1,2,3,4]) labels = set(gca(), 'xticklabels', ['Frogs', 'Hogs', 'Bogs', 'Slogs']) set(labels, 'rotation', 'vertical') show()"""), ('WINFONTS', "On windows with GTK, I'm getting lots of messages about not finding the Times font", r""" Apparently GTK changed the default pango font file, because this is a new problem. You can set font aliases in C:\GTK\etc\pango\pango.aliases. Add a line like
times = "times new roman,angsana new,mingliu,simsun,\\ gulimche,ms gothic,latha,mangal,code2000"Another alternative is suggested by Gary Ruben
I just installed Gimp 2 for windows along with the latest GTK+ runtime and noticed that it exhibited the same font problem I've been experiencing for ages with matplotlib. I was getting WARNING **: Couldn't load font "MS Sans Serif 8" falling back to "Sans 8" errors. It's addressed in their FAQ, http://www2.arnes.si/~sopjsimo/gimp/faq.html>, reproduced here: # I installed Gimp 2.0 on Windows 9x/ME or NT 4, and I'm getting a lot of messages saying ** (gimp-2.0.exe:4294830849): WARNING **: Couldn't load font "MS Sans Serif 8" falling back to "Sans 8". What should I do? # You have two options: * Go to Control Panel->Display properties->Apperance tab, and set all fonts to Tahoma (or any other TrueType font). * Uninstall GTK+ 2.2.4, then re-install it without the GTK-Wimp component. I took option B and now all is well with both Gimp and Matplotlib. I'm running Win98 and the Gimp FAQ entry hints that it may be a problem in Win98,ME and NT installations.""" ), ('FREETYPE2', "Why are my fonts not being rendered properly?", """ This is probably due to an outdated freetype2 library. The latest version is 2.1.9. See font manager docs for details. """ ), ('LEAKS', 'matplotlib appears to be leaking memory, what should I do?', """\ A number of severe memory leaks were fixed in the 0.54 and 0.60 matplotlib releases. These have been fixed, and here are no known leaks in matplotlib 0.63 or later with Numeric-23.5 or numarray >1.1. There is a leak in freetype 2.1.7 and earlier that was fixed in freetype 2.1.9. The memory leak situation has improved significantly as I've migrated almost all of the extension code to pycxx, and I use a number of unit tests to test leaks of various extension code components.
Below is a prototypical script that I use to diagnose and report memory leaks. Please use something like it when reporting leaks so I get an idea of the magnitude of the problem (ie bytes per figure). Also please provide your platform, matplotlib version, backend and as much information about the versions of the libraries you are using: freetype, png and zlib. It would also help if you posted code so I could look for any obvious coding errors vis-a-vis matplotlib.
Running the code below with 0.0000k bytes / per figure (matplotlib-0.63.0 / agg backend on linux with freetype 2.1.9, libpng1.2 and libz 1.1.4). If your numbers are much worse, it may be that you are doing something wrong, ie, not properly closing, reusing figure, etc, so please post some code to the list.
There is a fairly large leak in dot and a smaller leak in sometrue in numarray version 1.1, which matplotlib makes heavy use of. If you are using matplotlib with numarray, and are concerned about leaks, please use numarray CVS. Also, there appear to be small leaks in earlier versions of Numeric. My tests with Numeric-23.5 and numarray CVS (2004-09-29) revealed no detectable leaks.
import os, sys, time import matplotlib matplotlib.use('Agg') from pylab import * def report_memory(i): pid = os.getpid() a2 = os.popen('ps -p %d -o rss,sz' % pid).readlines() print i, ' ', a2[1], return int(a2[1].split()[1]) # take a memory snapshot on indStart and compare it with indEnd indStart, indEnd = 30, 150 for i in range(indEnd): ind = arange(100) xx = rand(len(ind)) figure(1) subplot(221) plot(ind, xx) subplot(222) X = rand(50,50) imshow(X) subplot(223) scatter(rand(50), rand(50)) subplot(224) pcolor(10*rand(50,50)) savefig('tmp%d' % i, dpi = 75) close(1) val = report_memory(i) # wait a few cycles for memory usage to stabilize if i==indStart: start = val end = val print 'Average memory consumed per loop: %1.4fk bytes\n' % \\ ((end-start)/float(indEnd-indStart))"""), ('GUIWIDGETS', "How do I control the properties of my figure window, eg title, size, etc...?", """ The only way currently to control the window size from the matlab interface is to set the figure size with the figsize option, eg figure(figsize=(10,12)). However, you can set window properties in a backend dependent manner with the figure manager instance.
manager = get_current_fig_manager()
manager = get_current_fig_manager() manager.window.set_title('hi mom')Of course, now your scripts won't work with other matplotlib backends.
In theory, we could abstract the essential window calls and expose them in a GUI neutral manner. We are trying to resist the urge to become a GUI wrapping library so we can focus on being a plotting library.
If you need a lot of control over GUI properties, you may want to skip the pylab interface and use the matplotlib API directly, eg build a GTK app which embeds matplotlib. See examples/embedding_in*.py in the matplotlib src distribution or at examples explaining how to embed matplotlib in your GUI of choice. """), ) @header@
- @footer@