FAQs = ( ('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. """), ('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.py
If 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. """), ('WRONGDIR', "When I try to import matplotlib.matlab, 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.out 
and post the results to the matplotlib-devel or matplotlib-users mailing lists. """), ('EXAMPLES', 'Where can I find examples of matplotlib code?', """ The matplotlib src distribution (*.zip for windows, *.tar.gz for linux and friends) comes with many examples in the examples directory. Notably, the windows installer does not come with the examples dirrectory. You can also get all the examples from examples. """), ('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 matplotlib.matlab, as described on backends
  >>> import matplotlib
  >>> matplotlib.use('Agg')
  >>> from matplotlib.matlab import *
Note that if you are using an IDE like pycrust, pythonwin, or IDLE, matplotlib.matlab may have already been loaded, and subsequent calls to use or from matplotlib.matlab 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 """), ('NUMARRAY', 'Does matplotlib work with numarray?', """ Yes. Todd Miller has added a numerix module which allows you to choose between Numeric or numarray at the prompt or in a config file. See numerix module for more information.

Some of the matplotlib extension code operates on Numeric/numarray arrays, eg the image and transforms modules. To get optimum performance, you should compile matplotlib with the proper flag for the library you will be using most. Set the NUMERIX variable in setup.py before building. Note that this is different from the numerix variable in .matplotlibrc. The former affects the matplotlib at compile time, the latter at run time. All of your matplotlib scripts should run without error regardless of these two settings, but to get optimum performance, they should agree. numarray builds for win32 are available on the download page."""), ('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. The most common cause is getting your numerix settings out of kilter. As indicated in the numarray faq, it is important that you compile matplotlib with the same numerix setting you use in your rc file. Failure to do so can cause up to a 30-fold performance hit in some cases.

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. """), ('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 matlab interface?', """ There is no official documentation yet, but there are a few resources

I'm working on some additional documentation but it is not ready yet. """), ('PY2EXE', 'Can I freeze matplotlib with py2exe', """ Yes. I have successfully frozen example scripts using the TkAgg, GTKAgg and WxAgg backends. One trick is to make sure that py2exe can find all the matplotlib data files. Recent versions of matplotlib (0.54.3 and later) support py2exe by looking in the py2exe dist dir for a matplotlibdata subdir. Thus if you're setup.py script looks like
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 matplotlib.matlab 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):

There is a long thread on the pygtk mailing list where Cousing Stanley got his gtk corrupted; read this thread, which is filled with good troubleshooting advice. """ ), ('WHICHBACKEND', 'Which backend should I use?', """ Each of the backends offers different strengths. I'll summarize some of them.

Image generation

For pure image generation (no GUI) you can choose from the Agg, Paint, GD, or PS backends. At this point, I advise people to use the agg backend because: It is likely that with time many of these limitiations or problems will be fixed on the other backends.

For publication submission or use with TeX, however, the postscript backend is naturally a good choice.

GUI

Currently there are several choices for GUIs: GTK, Wx, TkAgg, and GTKAgg, with different advantages. """), ('DATES', 'Can I plot dates?', r""" As of matplotlib-0.53, you can plot dates using a variety of datetime instances (eg python2.3 datetime module, mx.DateTime, raw epoch data). There are a number of converters, major and minor tick locators, and date formatters specialized for plotting dates. See see ticker and dates for details and usage and the examples date_demo1.py and date_demo2.py. """), ('TWOSCALES', 'Can I plot data with two y axes scales?', r""" As of matplotlib-0.53, there is support for this. See two_scales.py. """), ('MATHTEXT', 'Can I include math expressions in my figures?', r"""As of matplotlib-0.51, you can use TeX markup in any text element. Just use raw strings and enclose the strings with dollar signs, as in title(r'$\\alpha > \\beta_i$'). See screenshot and the mathtext documentation for usage, requirements and backend information. """), ('BATCHMODE', 'Can I just generate images without having a window popup?', """ The easiest way to do this is use an image backend, either Agg, GD or Paint if you want to generate PNG images, eg, for use in a web page, or PS if you want publication quality, scalable images. All of these backends run on all of the major platforms. One additional option on an X windows platform is to run the GTK backend under an Xvfb, which works nicely and is not too hard to setup. Contact jdhunter@ace.bsd.uchicago.edu for more information if you are interested setting this up."""), ('APPSERVER', 'Can I use matplotlib in a web application server?', """ Yes. matplotlb can be used with any web application server that can call python. It has been used with mod_python, xml_rpc, and other frameworks. You'll want to use one of the image backends; see image backends. Also to make small images appropriate for use on a web page, you may want to consider the Agg or GD backends, since they render small font rasters using freetype2 better than Paint, which currently use freetype1. You can work around the problem of small raster sizes by making your fonts appear larger for a given by decreasing the figure size and increasing the dpi. Eg,
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, Paint, GD, PS) but you do need it with the GUI (GTK, WX, TkAgg, GTKAgg) 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. 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 matplotlib.matlab 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 severe leaks in matplotlib as of 0.61. 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, I'm getting about anywhere between -5 to 5 bytes / per figure (matplotlib-0.60.2 / 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.

# Script to diagnose and report leaks
import os, sys, time
import matplotlib
matplotlib.use('Agg')
from matplotlib.matlab 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 = 10, 200
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)
    if i==indStart: start = val # wait a few cycles for memory usage to stabilize

end = val
print 'Average memory consumed per loop: %1.4fk bytes\n' % ((end-start)/float(indEnd-indStart))

"""), ) @header@

matplotlib FAQ

Questions

Answers

+ for name,q,a, in FAQs:

@q@

@a@

- @footer@