Frequently Asked Questions#

I don't see a figure window#

Please seeDebugging the figure windows not showing.

Why do I have so many ticks, and/or why are they out of order?#

One common cause for unexpected tick behavior is passing alist of stringsinstead of numbers or datetime objects. This can easily happen without noticewhen reading in a comma-delimited text file. Matplotlib treats lists of stringsascategorical variables(Plotting categorical variables), and by defaultputs one tick per category, and plots them in the order in which they aresupplied.

importmatplotlib.pyplotaspltimportnumpyasnpfig,ax=plt.subplots(1,2,layout='constrained',figsize=(6,2))ax[0].set_title('Ticks seem out of order / misplaced')x=['5','20','1','9']# stringsy=[5,20,1,9]ax[0].plot(x,y,'d')ax[0].tick_params(axis='x',labelcolor='red',labelsize=14)ax[1].set_title('Many ticks')x=[str(xx)forxxinnp.arange(100)]# stringsy=np.arange(100)ax[1].plot(x,y)ax[1].tick_params(axis='x',labelcolor='red',labelsize=14)

(Sourcecode,2x.png,png)

The solution is to convert the list of strings to numbers ordatetime objects (oftennp.asarray(numeric_strings,dtype='float') ornp.asarray(datetime_strings,dtype='datetime64[s]')).

For more information seeFixing too many ticks.

Determine the extent of Artists in the Figure#

Sometimes we want to know the extent of an Artist. MatplotlibArtist objectshave a methodArtist.get_window_extent that will usually return the extent ofthe artist in pixels. However, some artists, in particular text, must berendered at least once before their extent is known. Matplotlib suppliesFigure.draw_without_rendering, which should be called before callingget_window_extent.

Check whether a figure is empty#

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

For the purpose here, we define empty as: "The figure does not contain anyartists except its background patch." The exception for the background isnecessary, because by default every figure contains aRectangle as itsbackground patch. This definition could be checked via:

defis_empty(figure):"""    Return whether the figure contains no Artists (other than the default    background patch).    """contained_artists=figure.get_children()returnlen(contained_artists)<=1

We've decided not to include this as a figure method because this is only oneway of defining empty, and checking the above is only rarely necessary.Whether or not something has been added to the figure is usually definedwithin the context of the program.

The only reliable way to check whether a figure would render empty is toactually perform such a rendering and inspect the result.

Find all objects in a figure of a certain type#

Every Matplotlib artist (seeArtist tutorial) has a methodcalledfindobj() that can be used torecursively search the artist for any artists it may contain that meetsome criteria (e.g., match allLine2Dinstances or match some arbitrary filter function). For example, thefollowing snippet finds every object in the figure which has aset_color property and makes the object blue:

defmyfunc(x):returnhasattr(x,'set_color')foroinfig.findobj(myfunc):o.set_color('blue')

You can also filter on class instances:

importmatplotlib.textastextforoinfig.findobj(text.Text):o.set_fontstyle('italic')

Prevent ticklabels from having an offset#

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

ax.xaxis.get_major_formatter().set_useOffset(False)

setrcParams["axes.formatter.useoffset"] (default:True), or use a differentformatter. Seeticker for details.

Save transparent figures#

Thesavefig() command has a keyword argumenttransparent which, if 'True', will make the figure and axesbackgrounds transparent when saving, but will not affect the displayedimage on the screen.

If you need finer grained control, e.g., you do not want full transparencyor you want to affect the screen displayed version as well, you can setthe alpha properties directly. The figure has aRectangle instance calledpatchand the axes has a Rectangle instance calledpatch. You can setany 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 needall the figure elements to be transparent, there iscurrently no global alpha setting, but you can set the alpha channelon 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 formatssupport multi-page files. Currently, Matplotlib only provides multi-pageoutput to pdf files, using either the pdf or pgf backends, via thebackend_pdf.PdfPages andbackend_pgf.PdfPages classes.

Make room for tick labels#

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

Align my ylabels across multiple subplots#

If you have multiple subplots over one another, and the y data havedifferent scales, you can often get ylabels that do not alignvertically across the multiple subplots, which can be unattractive.By default, Matplotlib positions the x location of the ylabel so thatit does not overlap any of the y ticks. You can override this defaultbehavior by specifying the coordinates of the label. To learn how, seeAlign labels and titles

Control the draw order of plot elements#

The draw order of plot elements, and thus which elements will be on top, isdetermined by theset_zorder property.SeeZorder Demo for a detailed description.

Make the aspect ratio for plots equal#

The Axes propertyset_aspect() controls theaspect ratio of the axes. You can set it to be 'auto', 'equal', orsome ratio which controls the ratio:

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

SeeEqual axis aspect ratio for acomplete example.

Draw multiple y-axis scales#

A frequent request is to have two scales for the left and righty-axis, which is possible usingtwinx() (morethan two scales are not currently supported, though it is on the wishlist). This works pretty well, though there are some quirks when youare trying to interactively pan and zoom, because both scales do not getthe signals.

The approach usestwinx() (and its sistertwiny()) to use2 different axes,turning the axes rectangular frame off on the 2nd axes to keep it fromobscuring the first, and manually setting the tick locs and labels asdesired. You can use separatematplotlib.ticker formatters andlocators as desired because the two axes are independent.

(Sourcecode,2x.png,png)

SeePlots with different scales for acomplete example.

Generate images without having a window appear#

The recommended approach since Matplotlib 3.1 is to explicitly create a Figureinstance:

frommatplotlib.figureimportFigurefig=Figure()ax=fig.subplots()ax.plot([1,2,3])fig.savefig('myfig.png')

This prevents any interaction with GUI frameworks and the window manager.

It's alternatively still possible to use the pyplot interface: instead ofcallingmatplotlib.pyplot.show, callmatplotlib.pyplot.savefig. In thatcase, you must close the figure after saving it. Not closing the figure causesa memory leak, because pyplot keeps references to all not-yet-shown figures.

importmatplotlib.pyplotaspltplt.plot([1,2,3])plt.savefig('myfig.png')plt.close()

See also

Embed in a web application server (Flask) forinformation about running matplotlib inside of a web application.

Work with threads#

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

You may be able to work on separate figures from separate threads. However,you must in that case use anon-interactive backend (typically Agg), becausemost GUI backendsrequire being run from the main thread as well.

Get help#

There are a number of good resources for getting help with Matplotlib.There is a good chance your question has already been asked:

If you are unable to find an answer to your question through search, pleaseprovide the following information in your e-mail to themailing list:

  • Your operating system (Linux/Unix users: post the output ofuname-a).

  • Matplotlib version:

    python-c"import matplotlib; print(matplotlib.__version__)"
  • Where you obtained Matplotlib (e.g., your Linux distribution's packages,GitHub, PyPI, orAnaconda).

  • Any customizations to yourmatplotlibrc file (seeCustomizing Matplotlib with style sheets and rcParams).

  • If the problem is reproducible, please try to provide aminimal, standalonePython script that demonstrates the problem. This isthe critical step.If you can't post a piece of code that we can run and reproduce your error,the chances of getting help are significantly diminished. Very often, themere act of trying to minimize your code to the smallest bit that producesthe error will help you find a bug inyour code that is causing theproblem.

  • Matplotlib provides debugging information through thelogging library, anda helper function to set the logging level: one can call

    plt.set_loglevel("INFO")# or "DEBUG" for more info

    to obtain this debugging information.

    Standard functions from thelogging module are also applicable; e.g. onecould calllogging.basicConfig(level="DEBUG") even before importingMatplotlib (this is in particular necessary to get the logging info emittedduring Matplotlib's import), or attach a custom handler to the "matplotlib"logger. This may be useful if you use a custom logging configuration.

If you compiled Matplotlib yourself, please also provide:

  • your compiler version -- e.g.,gcc--version.

  • the output of:

    pipinstall--verbose

    The beginning of the build output contains lots of details about yourplatform that are useful for the Matplotlib developers to diagnose yourproblem.

If you compiled an older version of Matplotlib using the pre-Meson build system, insteadprovide:

  • any changes you have made tosetup.py/setupext.py,

  • the output of:

    rm-rfbuildpythonsetup.pybuild

Including this information in your first e-mail to the mailing listwill save a lot of time.

You will likely get a faster response writing to the mailing list thanfiling a bug in the bug tracker. Most developers check the bugtracker only periodically. If your problem has been determined to bea bug and cannot be quickly solved, you may be asked to file a bug inthe tracker so the issue doesn't get lost.