matplotlib#

An object-oriented plotting library.

A procedural interface is provided by the companion pyplot module,which may be imported directly, e.g.:

importmatplotlib.pyplotasplt

or using ipython:

ipython

at your terminal, followed by:

In[1]:%matplotlibIn[2]:importmatplotlib.pyplotasplt

at the ipython shell prompt.

For the most part, direct use of the explicit object-oriented library isencouraged when programming; the implicit pyplot interface is primarily forworking interactively. The exceptions to this suggestion are the pyplotfunctionspyplot.figure,pyplot.subplot,pyplot.subplots, andpyplot.savefig, which can greatly simplify scripting. SeeMatplotlib Application Interfaces (APIs) for an explanation of the tradeoffs between the implicitand explicit interfaces.

Modules include:

matplotlib.axes

TheAxes class. Most pyplot functions are wrappers forAxes methods. The axes module is the highest level of OOaccess to the library.

matplotlib.figure

TheFigure class.

matplotlib.artist

TheArtist base class for all classes that draw things.

matplotlib.lines

TheLine2D class for drawing lines and markers.

matplotlib.patches

Classes for drawing polygons.

matplotlib.text

TheText andAnnotation classes.

matplotlib.image

TheAxesImage andFigureImage classes.

matplotlib.collections

Classes for efficient drawing of groups of lines or polygons.

matplotlib.colors

Color specifications and making colormaps.

matplotlib.cm

Colormaps, and theScalarMappable mixin class for providing colormapping functionality to other classes.

matplotlib.ticker

Calculation of tick mark locations and formatting of tick labels.

matplotlib.backends

A subpackage with modules for various GUI libraries and output formats.

The base matplotlib namespace includes:

rcParams

Default configuration settings; their defaults may be overridden usingamatplotlibrc file.

use

Setting the Matplotlib backend. This should be called before anyfigure is created, because it is not possible to switch betweendifferent GUI backends after that.

The following environment variables can be used to customize the behavior:

MPLBACKEND

This optional variable can be set to choose the Matplotlib backend. SeeWhat is a backend?.

MPLCONFIGDIR

This is the directory used to store user customizations toMatplotlib, as well as some caches to improve performance. IfMPLCONFIGDIR is not defined,HOME/.config/matplotlibandHOME/.cache/matplotlib are used on Linux, andHOME/.matplotlib on other platforms, if they arewritable. Otherwise, the Python standard library'stempfile.gettempdiris used to find a base directory in which thematplotlibsubdirectory is created.

Matplotlib was initially written by John D. Hunter (1968-2012) and is nowdeveloped and maintained by a host of others.

Occasionally the internal documentation (python docstrings) will referto MATLAB®, a registered trademark of The MathWorks, Inc.

Backend management#

matplotlib.use(backend,*,force=True)[source]#

Select the backend used for rendering and GUI integration.

If pyplot is already imported,switch_backend is usedand if the new backend is different than the current backend, all Figureswill be closed.

Parameters:
backendstr

The backend to switch to. This can either be one of the standardbackend names, which are case-insensitive:

  • interactive backends:GTK3Agg, GTK3Cairo, GTK4Agg, GTK4Cairo, MacOSX, nbAgg, notebook, QtAgg,QtCairo, TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo, Qt5Agg, Qt5Cairo

  • non-interactive backends:agg, cairo, pdf, pgf, ps, svg, template

or a string of the form:module://my.module.name.

notebook is a synonym for nbAgg.

Switching to an interactive backend is not possible if an unrelatedevent loop has already been started (e.g., switching to GTK3Agg if aTkAgg window has already been opened). Switching to a non-interactivebackend is always possible.

forcebool, default: True

If True (the default), raise anImportError if the backend cannot beset up (either because it fails to import, or because an incompatibleGUI interactive framework is already running); if False, silentlyignore the failure.

matplotlib.get_backend(*,auto_select=True)[source]#

Return the name of the current backend.

Parameters:
auto_selectbool, default: True

Whether to trigger backend resolution if no backend has beenselected so far. If True, this ensures that a valid backendis returned. If False, this returns None if no backend has beenselected so far.

Added in version 3.10.

Provisional

Theauto_select flag is provisional. It may be changed or removedwithout prior warning.

matplotlib.interactive(b)[source]#

Set whether to redraw after every plotting command (e.g.pyplot.xlabel).

matplotlib.is_interactive()[source]#

Return whether to redraw after every plotting command.

Note

This function is only intended for use in backends. End users shouldusepyplot.isinteractive instead.

Default values and styling#

matplotlib.rcParams[source]#

An instance ofRcParams for handling default Matplotlib values.

classmatplotlib.RcParams(*args,**kwargs)[source]#

A dict-like key-value store for config parameters, including validation.

Validating functions are defined and associated with rc parameters inmatplotlib.rcsetup.

The list of rcParams is:

  • _internal.classic_mode

  • agg.path.chunksize

  • animation.bitrate

  • animation.codec

  • animation.convert_args

  • animation.convert_path

  • animation.embed_limit

  • animation.ffmpeg_args

  • animation.ffmpeg_path

  • animation.frame_format

  • animation.html

  • animation.writer

  • axes.autolimit_mode

  • axes.axisbelow

  • axes.edgecolor

  • axes.facecolor

  • axes.formatter.limits

  • axes.formatter.min_exponent

  • axes.formatter.offset_threshold

  • axes.formatter.use_locale

  • axes.formatter.use_mathtext

  • axes.formatter.useoffset

  • axes.grid

  • axes.grid.axis

  • axes.grid.which

  • axes.labelcolor

  • axes.labelpad

  • axes.labelsize

  • axes.labelweight

  • axes.linewidth

  • axes.prop_cycle

  • axes.spines.bottom

  • axes.spines.left

  • axes.spines.right

  • axes.spines.top

  • axes.titlecolor

  • axes.titlelocation

  • axes.titlepad

  • axes.titlesize

  • axes.titleweight

  • axes.titley

  • axes.unicode_minus

  • axes.xmargin

  • axes.ymargin

  • axes.zmargin

  • axes3d.automargin

  • axes3d.depthshade

  • axes3d.depthshade_minalpha

  • axes3d.grid

  • axes3d.mouserotationstyle

  • axes3d.trackballborder

  • axes3d.trackballsize

  • axes3d.xaxis.panecolor

  • axes3d.yaxis.panecolor

  • axes3d.zaxis.panecolor

  • backend

  • backend_fallback

  • boxplot.bootstrap

  • boxplot.boxprops.color

  • boxplot.boxprops.linestyle

  • boxplot.boxprops.linewidth

  • boxplot.capprops.color

  • boxplot.capprops.linestyle

  • boxplot.capprops.linewidth

  • boxplot.flierprops.color

  • boxplot.flierprops.linestyle

  • boxplot.flierprops.linewidth

  • boxplot.flierprops.marker

  • boxplot.flierprops.markeredgecolor

  • boxplot.flierprops.markeredgewidth

  • boxplot.flierprops.markerfacecolor

  • boxplot.flierprops.markersize

  • boxplot.meanline

  • boxplot.meanprops.color

  • boxplot.meanprops.linestyle

  • boxplot.meanprops.linewidth

  • boxplot.meanprops.marker

  • boxplot.meanprops.markeredgecolor

  • boxplot.meanprops.markerfacecolor

  • boxplot.meanprops.markersize

  • boxplot.medianprops.color

  • boxplot.medianprops.linestyle

  • boxplot.medianprops.linewidth

  • boxplot.notch

  • boxplot.patchartist

  • boxplot.showbox

  • boxplot.showcaps

  • boxplot.showfliers

  • boxplot.showmeans

  • boxplot.vertical

  • boxplot.whiskerprops.color

  • boxplot.whiskerprops.linestyle

  • boxplot.whiskerprops.linewidth

  • boxplot.whiskers

  • contour.algorithm

  • contour.corner_mask

  • contour.linewidth

  • contour.negative_linestyle

  • date.autoformatter.day

  • date.autoformatter.hour

  • date.autoformatter.microsecond

  • date.autoformatter.minute

  • date.autoformatter.month

  • date.autoformatter.second

  • date.autoformatter.year

  • date.converter

  • date.epoch

  • date.interval_multiples

  • docstring.hardcopy

  • errorbar.capsize

  • figure.autolayout

  • figure.constrained_layout.h_pad

  • figure.constrained_layout.hspace

  • figure.constrained_layout.use

  • figure.constrained_layout.w_pad

  • figure.constrained_layout.wspace

  • figure.dpi

  • figure.edgecolor

  • figure.facecolor

  • figure.figsize

  • figure.frameon

  • figure.hooks

  • figure.labelsize

  • figure.labelweight

  • figure.max_open_warning

  • figure.raise_window

  • figure.subplot.bottom

  • figure.subplot.hspace

  • figure.subplot.left

  • figure.subplot.right

  • figure.subplot.top

  • figure.subplot.wspace

  • figure.titlesize

  • figure.titleweight

  • font.cursive

  • font.enable_last_resort

  • font.family

  • font.fantasy

  • font.monospace

  • font.sans-serif

  • font.serif

  • font.size

  • font.stretch

  • font.style

  • font.variant

  • font.weight

  • grid.alpha

  • grid.color

  • grid.linestyle

  • grid.linewidth

  • hatch.color

  • hatch.linewidth

  • hist.bins

  • image.aspect

  • image.cmap

  • image.composite_image

  • image.interpolation

  • image.interpolation_stage

  • image.lut

  • image.origin

  • image.resample

  • interactive

  • keymap.back

  • keymap.copy

  • keymap.forward

  • keymap.fullscreen

  • keymap.grid

  • keymap.grid_minor

  • keymap.help

  • keymap.home

  • keymap.pan

  • keymap.quit

  • keymap.quit_all

  • keymap.save

  • keymap.xscale

  • keymap.yscale

  • keymap.zoom

  • legend.borderaxespad

  • legend.borderpad

  • legend.columnspacing

  • legend.edgecolor

  • legend.facecolor

  • legend.fancybox

  • legend.fontsize

  • legend.framealpha

  • legend.frameon

  • legend.handleheight

  • legend.handlelength

  • legend.handletextpad

  • legend.labelcolor

  • legend.labelspacing

  • legend.loc

  • legend.markerscale

  • legend.numpoints

  • legend.scatterpoints

  • legend.shadow

  • legend.title_fontsize

  • lines.antialiased

  • lines.color

  • lines.dash_capstyle

  • lines.dash_joinstyle

  • lines.dashdot_pattern

  • lines.dashed_pattern

  • lines.dotted_pattern

  • lines.linestyle

  • lines.linewidth

  • lines.marker

  • lines.markeredgecolor

  • lines.markeredgewidth

  • lines.markerfacecolor

  • lines.markersize

  • lines.scale_dashes

  • lines.solid_capstyle

  • lines.solid_joinstyle

  • macosx.window_mode

  • markers.fillstyle

  • mathtext.bf

  • mathtext.bfit

  • mathtext.cal

  • mathtext.default

  • mathtext.fallback

  • mathtext.fontset

  • mathtext.it

  • mathtext.rm

  • mathtext.sf

  • mathtext.tt

  • patch.antialiased

  • patch.edgecolor

  • patch.facecolor

  • patch.force_edgecolor

  • patch.linewidth

  • path.effects

  • path.simplify

  • path.simplify_threshold

  • path.sketch

  • path.snap

  • pcolor.shading

  • pcolormesh.snap

  • pdf.compression

  • pdf.fonttype

  • pdf.inheritcolor

  • pdf.use14corefonts

  • pgf.preamble

  • pgf.rcfonts

  • pgf.texsystem

  • polaraxes.grid

  • ps.distiller.res

  • ps.fonttype

  • ps.papersize

  • ps.useafm

  • ps.usedistiller

  • savefig.bbox

  • savefig.directory

  • savefig.dpi

  • savefig.edgecolor

  • savefig.facecolor

  • savefig.format

  • savefig.orientation

  • savefig.pad_inches

  • savefig.transparent

  • scatter.edgecolors

  • scatter.marker

  • svg.fonttype

  • svg.hashsalt

  • svg.id

  • svg.image_inline

  • text.antialiased

  • text.color

  • text.hinting

  • text.hinting_factor

  • text.kerning_factor

  • text.latex.preamble

  • text.parse_math

  • text.usetex

  • timezone

  • tk.window_focus

  • toolbar

  • webagg.address

  • webagg.open_in_browser

  • webagg.port

  • webagg.port_retries

  • xaxis.labellocation

  • xtick.alignment

  • xtick.bottom

  • xtick.color

  • xtick.direction

  • xtick.labelbottom

  • xtick.labelcolor

  • xtick.labelsize

  • xtick.labeltop

  • xtick.major.bottom

  • xtick.major.pad

  • xtick.major.size

  • xtick.major.top

  • xtick.major.width

  • xtick.minor.bottom

  • xtick.minor.ndivs

  • xtick.minor.pad

  • xtick.minor.size

  • xtick.minor.top

  • xtick.minor.visible

  • xtick.minor.width

  • xtick.top

  • yaxis.labellocation

  • ytick.alignment

  • ytick.color

  • ytick.direction

  • ytick.labelcolor

  • ytick.labelleft

  • ytick.labelright

  • ytick.labelsize

  • ytick.left

  • ytick.major.left

  • ytick.major.pad

  • ytick.major.right

  • ytick.major.size

  • ytick.major.width

  • ytick.minor.left

  • ytick.minor.ndivs

  • ytick.minor.pad

  • ytick.minor.right

  • ytick.minor.size

  • ytick.minor.visible

  • ytick.minor.width

  • ytick.right

find_all(pattern)[source]#

Return the subset of this RcParams dictionary whose keys match,usingre.search(), the givenpattern.

Note

Changes to the returned dictionary arenot propagated tothe parent RcParams dictionary.

copy()[source]#

Copy this RcParams instance.

matplotlib.rc_context(rc=None,fname=None)[source]#

Return a context manager for temporarily changing rcParams.

ThercParams["backend"] will not be reset by the context manager.

rcParams changed both through the context manager invocation andin the body of the context will be reset on context exit.

Parameters:
rcdict

The rcParams to temporarily set.

fnamestr or path-like

A file with Matplotlib rc settings. If bothfname andrc are given,settings fromrc take precedence.

Examples

Passing explicit values via a dict:

withmpl.rc_context({'interactive':False}):fig,ax=plt.subplots()ax.plot(range(3),range(3))fig.savefig('example.png')plt.close(fig)

Loading settings from a file:

withmpl.rc_context(fname='print.rc'):plt.plot(x,y)# uses 'print.rc'

Setting in the context body:

withmpl.rc_context():# will be resetmpl.rcParams['lines.linewidth']=5plt.plot(x,y)
matplotlib.rc(group,**kwargs)[source]#

Set the currentrcParams.group is the grouping for the rc, e.g.,forlines.linewidth the group islines, foraxes.facecolor, the group isaxes, and so on. Group mayalso be a list or tuple of group names, e.g., (xtick,ytick).kwargs is a dictionary attribute name/value pairs, e.g.,:

rc('lines',linewidth=2,color='r')

sets the currentrcParams and is equivalent to:

rcParams['lines.linewidth']=2rcParams['lines.color']='r'

The following aliases are available to save typing for interactive users:

Alias

Property

'lw'

'linewidth'

'ls'

'linestyle'

'c'

'color'

'fc'

'facecolor'

'ec'

'edgecolor'

'mew'

'markeredgewidth'

'aa'

'antialiased'

'sans'

'sans-serif'

Thus you could abbreviate the above call as:

rc('lines',lw=2,c='r')

Note you can use python's kwargs dictionary facility to storedictionaries of default parameters. e.g., you can customize thefont rc as follows:

font={'family':'monospace','weight':'bold','size':'larger'}rc('font',**font)# pass in the font dict as kwargs

This enables you to easily switch between several configurations. Usematplotlib.style.use('default') orrcdefaults() torestore the defaultrcParams after changes.

Notes

Similar functionality is available by using the normal dict interface, i.e.rcParams.update({"lines.linewidth":2,...}) (butrcParams.updatedoes not support abbreviations or grouping).

matplotlib.rcdefaults()[source]#

Restore thercParams from Matplotlib's internal default style.

Style-blacklistedrcParams (defined inmatplotlib.style.core.STYLE_BLACKLIST) are not updated.

See also

matplotlib.rc_file_defaults

Restore thercParams from the rc file originally loaded by Matplotlib.

matplotlib.style.use

Use a specific style file. Callstyle.use('default') to restore the default style.

matplotlib.rc_file_defaults()[source]#

Restore thercParams from the original rc file loaded by Matplotlib.

Style-blacklistedrcParams (defined inmatplotlib.style.core.STYLE_BLACKLIST) are not updated.

matplotlib.rc_file(fname,*,use_default_template=True)[source]#

UpdatercParams from file.

Style-blacklistedrcParams (defined inmatplotlib.style.core.STYLE_BLACKLIST) are not updated.

Parameters:
fnamestr or path-like

A file with Matplotlib rc settings.

use_default_templatebool

If True, initialize with default parameters before updating with thosein the given file. If False, the current configuration persistsand only the parameters specified in the file are updated.

matplotlib.rc_params(fail_on_error=False)[source]#

Construct aRcParams instance from the default Matplotlib rc file.

matplotlib.rc_params_from_file(fname,fail_on_error=False,use_default_template=True)[source]#

Construct aRcParams from filefname.

Parameters:
fnamestr or path-like

A file with Matplotlib rc settings.

fail_on_errorbool

If True, raise an error when the parser fails to convert a parameter.

use_default_templatebool

If True, initialize with default parameters before updating with thosein the given file. If False, the configuration class only contains theparameters specified in the file. (Useful for updating dicts.)

matplotlib.get_configdir()[source]#

Return the string path of the configuration directory.

The directory is chosen as follows:

  1. If the MPLCONFIGDIR environment variable is supplied, choose that.

  2. On Linux, follow the XDG specification and look first in$XDG_CONFIG_HOME, if defined, or$HOME/.config. On otherplatforms, choose$HOME/.matplotlib.

  3. If the chosen directory exists and is writable, use that as theconfiguration directory.

  4. Else, create a temporary directory, and use it as the configurationdirectory.

matplotlib.matplotlib_fname()[source]#

Get the location of the config file.

The file location is determined in the following order

  • $PWD/matplotlibrc

  • $MATPLOTLIBRC if it is not a directory

  • $MATPLOTLIBRC/matplotlibrc

  • $MPLCONFIGDIR/matplotlibrc

  • On Linux,
    • $XDG_CONFIG_HOME/matplotlib/matplotlibrc (if$XDG_CONFIG_HOMEis defined)

    • or$HOME/.config/matplotlib/matplotlibrc (if$XDG_CONFIG_HOMEis not defined)

  • On other platforms,-$HOME/.matplotlib/matplotlibrc if$HOME is defined

  • Lastly, it looks in$MATPLOTLIBDATA/matplotlibrc, which should alwaysexist.

matplotlib.get_data_path()[source]#

Return the path to Matplotlib data.

Logging#

matplotlib.set_loglevel(level)[source]#

Configure Matplotlib's logging levels.

Matplotlib uses the standard librarylogging framework under the rootlogger 'matplotlib'. This is a helper function to:

  • set Matplotlib's root logger level

  • set the root logger handler's level, creating the handlerif it does not exist yet

Typically, one should callset_loglevel("info") orset_loglevel("debug") to get additional debugging information.

Users or applications that are installing their own logging handlersmay want to directly manipulatelogging.getLogger('matplotlib') ratherthan use this function.

Parameters:
level{"notset", "debug", "info", "warning", "error", "critical"}

The log level of the handler.

Notes

The first time this function is called, an additional handler is attachedto Matplotlib's root handler; this handler is reused every time and thisfunction simply manipulates the logger and handler's level.

Colormaps and color sequences#

matplotlib.colormaps[source]#

Container for colormaps that are known to Matplotlib by name.

The universal registry instance ismatplotlib.colormaps. There should beno need for users to instantiateColormapRegistry themselves.

Read access uses a dict-like interface mapping names toColormaps:

importmatplotlibasmplcmap=mpl.colormaps['viridis']

ReturnedColormaps are copies, so that their modification does notchange the global definition of the colormap.

Additional colormaps can be added viaColormapRegistry.register:

mpl.colormaps.register(my_colormap)

To get a list of all registered colormaps, you can do:

frommatplotlibimportcolormapslist(colormaps)
matplotlib.color_sequences[source]#

Container for sequences of colors that are known to Matplotlib by name.

The universal registry instance ismatplotlib.color_sequences. Thereshould be no need for users to instantiateColorSequenceRegistrythemselves.

Read access uses a dict-like interface mapping names to lists of colors:

importmatplotlibasmplcolors=mpl.color_sequences['tab10']

For a list of built in color sequences, seeNamed color sequences.The returned lists are copies, so that their modification does not changethe global definition of the color sequence.

Additional color sequences can be added viaColorSequenceRegistry.register:

mpl.color_sequences.register('rgb',['r','g','b'])

Miscellaneous#

classmatplotlib.MatplotlibDeprecationWarning[source]#

A class for issuing deprecation warnings for Matplotlib users.

matplotlib.get_cachedir()[source]#

Return the string path of the cache directory.

The procedure used to find the directory is the same as forget_configdir, except using$XDG_CACHE_HOME/$HOME/.cache instead.