How-to

Check whether a figure is empty

Empty can actually mean different things. Does the figure contain any artists? Does a figure with an empty Axes still count as empty? Is the figure empty if it was rendered pure white (there may be artists present, but they could be outside the drawing area or transparent)?

For the purpose here, we define empty as: "The figure does not contain any artists except it's background patch." The exception for the background is necessary, because by default every figure contains a Rectangle as it's background patch. This definition could be checked via:

def is_empty(figure):
    """
    Return whether the figure contains no Artists (other than the default
    background patch).
    """
    contained_artists = figure.get_children()
    return len(contained_artists) <= 1

We've decided not to include this as a figure method because this is only one way of defining empty, and checking the above is only rarely necessary. Usually the user or program handling the figure know if they have added something to the figure.

Checking whether a figure would render empty cannot be reliably checked except by actually rendering the figure and investigating the rendered result.

Find all objects in a figure of a certain type

Every Matplotlib artist (see Artist tutorial) has a method called findobj() that can be used to recursively search the artist for any artists it may contain that meet some criteria (e.g., match all Line2D instances or match some arbitrary filter function). For example, the following snippet finds every object in the figure which has a set_color property and makes the object blue:

def myfunc(x):
    return hasattr(x, 'set_color')

for o in fig.findobj(myfunc):
    o.set_color('blue')

You can also filter on class instances:

import matplotlib.text as text
for o in fig.findobj(text.Text):
    o.set_fontstyle('italic')

Prevent ticklabels from having an offset

The default formatter will use an offset to reduce the length of the ticklabels. To turn this feature off on a per-axis basis:

ax.get_xaxis().get_major_formatter().set_useOffset(False)

set rcParams["axes.formatter.useoffset"] (default: True), or use a different formatter. See ticker for details.

Save transparent figures

The savefig() command has a keyword argument transparent which, if 'True', will make the figure and axes backgrounds transparent when saving, but will not affect the displayed image on the screen.

If you need finer grained control, e.g., you do not want full transparency or you want to affect the screen displayed version as well, you can set the alpha properties directly. The figure has a Rectangle instance called patch and the axes has a Rectangle instance called patch. You can set any property on them directly (facecolor, edgecolor, linewidth, linestyle, alpha). e.g.:

fig = plt.figure()
fig.patch.set_alpha(0.5)
ax = fig.add_subplot(111)
ax.patch.set_alpha(0.5)

If you need all the figure elements to be transparent, there is currently no global alpha setting, but you can set the alpha channel on individual elements, e.g.:

ax.plot(x, y, alpha=0.5)
ax.set_xlabel('volts', alpha=0.5)

Save multiple plots to one pdf file

Many image file formats can only have one image per file, but some formats support multi-page files. Currently only the pdf backend has support for this. To make a multi-page pdf file, first initialize the file:

from matplotlib.backends.backend_pdf import PdfPages
pp = PdfPages('multipage.pdf')

You can give the PdfPages object to savefig(), but you have to specify the format:

plt.savefig(pp, format='pdf')

An easier way is to call PdfPages.savefig:

pp.savefig()

Finally, the multipage pdf object has to be closed:

pp.close()

The same can be done using the pgf backend:

from matplotlib.backends.backend_pgf import PdfPages

Make room for tick labels

By default, Matplotlib uses fixed percentage margins around subplots. This can lead to labels overlapping or being cut off at the figure boundary. There are multiple ways to fix this:

Align my ylabels across multiple subplots

If you have multiple subplots over one another, and the y data have different scales, you can often get ylabels that do not align vertically across the multiple subplots, which can be unattractive. By default, Matplotlib positions the x location of the ylabel so that it does not overlap any of the y ticks. You can override this default behavior by specifying the coordinates of the label. The example below shows the default behavior in the left subplots, and the manual setting in the right subplots.

../_images/sphx_glr_align_ylabels_001.png

Control the draw order of plot elements

The draw order of plot elements, and thus which elements will be on top, is determined by the set_zorder property. See Zorder Demo for a detailed description.

Make the aspect ratio for plots equal

The Axes property set_aspect() controls the aspect ratio of the axes. You can set it to be 'auto', 'equal', or some ratio which controls the ratio:

ax = fig.add_subplot(111, aspect='equal')

See Equal axis aspect ratio for a complete example.

Draw multiple y-axis scales

A frequent request is to have two scales for the left and right y-axis, which is possible using twinx() (more than two scales are not currently supported, though it is on the wish list). This works pretty well, though there are some quirks when you are trying to interactively pan and zoom, because both scales do not get the signals.

The approach uses twinx() (and its sister twiny()) to use 2 different axes, turning the axes rectangular frame off on the 2nd axes to keep it from obscuring the first, and manually setting the tick locs and labels as desired. You can use separate matplotlib.ticker formatters and locators as desired because the two axes are independent.

(Source code, png, pdf)

../_images/howto_faq-1.png

See Plots with different scales for a complete example.

Generate images without having a window appear

Simply do not call show, and directly save the figure to the desired format:

import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
plt.savefig('myfig.png')

See also

Embedding in a web application server (Flask) for information about running matplotlib inside of a web application.

Work with threads

Matplotlib is not thread-safe: in fact, there are known race conditions that affect certain artists. Hence, if you work with threads, it is your responsibility to set up the proper locks to serialize access to Matplotlib artists.

You may be able to work on separate figures from separate threads. However, you must in that case use a non-interactive backend (typically Agg), because most GUI backends require being run from the main thread as well.