New figure.Figure.add_subfigure and figure.Figure.subfigures
functionalities allow creating virtual figures within figures. Similar nesting
was previously done with nested gridspecs (see
). However, this did
not allow localized figure artists (e.g., a colorbar or suptitle) that only
pertained to each subgridspec.
Correspondingly, the behavior of the functions to get the current Axes
(pyplot.gca, figure.Figure.gca) has changed. In the past, these functions
accepted keyword arguments. If the keyword arguments matched an
already-existing Axes, then that Axes would be returned, otherwise new Axes
would be created with those keyword arguments. Now, the keyword arguments are
only considered if there are no Axes at all in the current figure. In a future
release, these functions will not accept keyword arguments at all.
add_subplot/add_axes gained an axes_class parameter
In particular, mpl_toolkits Axes subclasses can now be idiomatically used
using, e.g., fig.add_subplot(axes_class=mpl_toolkits.axislines.Axes)
Subplot and subplot2grid can now work with constrained layout
constrained_layout depends on a single GridSpec for each logical layout
on a figure. Previously, pyplot.subplot and pyplot.subplot2grid added a
new GridSpec each time they were called and were therefore incompatible
with constrained_layout.
Now subplot attempts to reuse the GridSpec if the number of rows and
columns is the same as the top level GridSpec already in the figure, i.e.,
plt.subplot(2,1,2) will use the same GridSpec as plt.subplot(2,1,1)
and the constrained_layout=True option to Figure will work.
In contrast, mixing nrows and ncols will not work with
constrained_layout: plt.subplot(2,2,1) followed by plt.subplots(2,1,2) will still produce two GridSpecs, and constrained_layout=True will
give bad results. In order to get the desired effect, the second call can
specify the cells the second Axes is meant to cover: plt.subplots(2,2,(2,4)), or the more Pythonic plt.subplot2grid((2,2),(0,1),rowspan=2) can
be used.
Plotting methods
axline supports transform parameter
axline now supports the transform parameter, which applies to the
points xy1, xy2. The slope (if given) is always in data coordinates.
For example, this can be used with ax.transAxes for drawing lines with a
fixed slope. In the following plot, the line appears through the same point on
both Axes, even though they show different data limits.
A new Axes.bar_label method has been added for auto-labeling bar charts.
Example of the new automatic labeling.
A list of hatches can be specified to bar and barh
Similar to some other rectangle properties, it is now possible to hand a list
of hatch styles to bar and barh in order to create
bars with different hatch styles, e.g.
Formerly, Axes.errorbar incorrectly skipped the Axes property cycle if a
color was explicitly specified, even if the property cycler was for other
properties (such as line style). Now, Axes.errorbar will advance the Axes
property cycle as done for Axes.plot, i.e., as long as all properties in the
cycler are not explicitly passed.
For example, the following will cycle through the line styles:
x=np
errorbarerrorevery parameter matches markevery
Similar to the markevery parameter to plot, the errorevery
parameter of errorbar now accept slices and NumPy fancy indexes (which
must match the size of x).
Axes.spines is now a dedicated container class Spines for a set of
Spines instead of an OrderedDict. On top of dict-like access,
Axes.spines now also supports some pandas.Series-like features.
Accessing single elements by item or by attribute:
ax
New stairs method and StepPatch artist
pyplot.stairs and the underlying artist StepPatch
provide a cleaner interface for plotting stepwise constant functions for the
common case that you know the step edges. This supersedes many use cases of
pyplot.step, for instance when plotting the output of numpy.histogram.
For both the artist and the function, the x-like edges input is one element
longer than the y-like values input
Added orientation parameter for stem plots
By default, stem lines are vertical. They can be changed to horizontal using
the orientation parameter of Axes.stem or pyplot.stem:
Angles specified on the Bracket arrow styles (]-[, ]-, -[, or
|-| passed to arrowstyle parameter of FancyArrowPatch) are now
applied. Previously, the angleA and angleB options were allowed, but did
nothing.
The new TickedStroke patheffect can be used to produce lines with a ticked
style. This can be used to, e.g., distinguish the valid and invalid sides of
the constraint boundaries in the solution space of optimizations.
Colors and colormaps
Collection color specification and mapping
Reworking the handling of color mapping and the keyword arguments for
facecolor and edgecolor has resulted in three behavior changes:
Color mapping can be turned off by calling Collection.set_array(None).
Previously, this would have no effect.
When a mappable array is set, with facecolor='none' and
edgecolor='face', both the faces and the edges are left uncolored.
Previously the edges would be color-mapped.
When a mappable array is set, with facecolor='none' and
edgecolor='red', the edges are red. This addresses Issue #1302.
Previously the edges would be color-mapped.
Transparency (alpha) can be set as an array in collections
Previously, the alpha value controlling transparency in collections could be
specified only as a scalar applied to all elements in the collection. For
example, all the markers in a scatter plot, or all the quadrilaterals
in a pcolormesh plot, would have the same alpha value.
Now it is possible to supply alpha as an array with one value for each element
(marker, quadrilateral, etc.) in a collection.
pcolormesh has improved transparency handling by enabling snapping
Due to how the snapping keyword argument was getting passed to the Agg backend,
previous versions of Matplotlib would appear to show lines between the grid
edges of a mesh with transparency. This version now applies snapping by
default. To restore the old behavior (e.g., for test images), you may set
rcParams["pcolormesh.snap"] (default: True) to False.
The matplotlib.colors.Colormap object now has image representations for
IPython / Jupyter backends. Cells returning a colormap on the last line will
display an image of the colormap.
Because the Colormap.set_bad, Colormap.set_under and Colormap.set_over
methods modify the colormap in place, the user must be careful to first make a
copy of the colormap if setting the extreme colors e.g. for a builtin colormap.
The new Colormap.with_extremes(bad=...,under=...,over=...) can be used to
first copy the colormap and set the extreme colors on that copy.
The new method is provided for API symmetry with
, but note that it suffers from the same issue as the
earlier individual setters.
matplotlib.cm.unregister_cmap allows users to remove a colormap that they have
previously registered.
New CenteredNorm for symmetrical data around a center
In cases where data is symmetrical around a center, for example, positive and
negative anomalies around a center zero, CenteredNorm is
a new norm that automatically creates a symmetrical mapping around the center.
This norm is well suited to be combined with a divergent colormap which uses an
unsaturated color in its center.
Shared-axes subplots tick label visibility is now correct for top or left labels
When calling subplots(...,sharex=True,sharey=True), Matplotlib
automatically hides x tick labels for Axes not in the first column and y tick
labels for Axes not in the last row. This behavior is incorrect if rcParams
specify that Axes should be labeled on the top (rcParams["xtick.labeltop"]=True) or on the right (rcParams["ytick.labelright"]=True).
Cases such as the following are now handled correctly (adjusting visibility as
needed on the first row and last column of Axes):
plt.rcParams["xtick.labelbottom"]=Falseplt
An iterable object with labels can be passed to Axes.plot
When plotting multiple datasets by passing 2D data as y value to
plot, labels for the datasets can be passed as a list, the length
matching the number of columns in y.
x=[1,2,3]y=[[1,2],
Fonts and Text
Text transform can rotate text direction
The new Text parameter transform_rotates_text now sets whether rotations
of the transform affect the text direction.
Example of the new transform_rotates_text parameter
matplotlib.mathtext now supports overset and underset LaTeX symbols
mathtext now supports overset and underset, called as
\overset{annotation}{body} or \underset{annotation}{body}, where
annotation is the text "above" or "below" the body.
math_fontfamily parameter to change Text font family
The new math_fontfamily parameter may be used to change the family of fonts
for each individual text element in a plot. If no parameter is set, the global
value rcParams["mathtext.fontset"] (default: 'dejavusans') will be used.
TextArea/AnchoredText support horizontalalignment
The horizontal alignment of text in a TextArea or AnchoredText may now be
specified, which is mostly effective for multiline text:
The new rcParams["date.interval_multiples"] (default: True) allows toggling between the dates locator
trying to pick ticks at set intervals (i.e., day 1 and 15 of the month), versus
evenly spaced ticks that start wherever the timeseries starts:
The AutoDateFormatter and ConciseDateFormatter now respect
rcParams["text.usetex"] (default: False), and will thus use fonts consistent with TeX rendering of the
default (non-date) formatter. TeX rendering may also be enabled/disabled by
passing the usetex parameter when creating the formatter instance.
In the following plot, both the x-axis (dates) and y-axis (numbers) now use the
same (TeX) font:
It is now possible to set rcParams["image.cmap"] (default: 'viridis') to a Colormap instance, such as a
colormap created with the new set_extremes above. (This can only
be done from Python code, not from the matplotlibrc file.)
Tick and tick label colors can be set independently using rcParams
Previously, rcParams["xtick.color"] (default: 'black') defined both the tick color and the label color.
The label color can now be set independently using rcParams["xtick.labelcolor"] (default: 'inherit'). It
defaults to 'inherit' which will take the value from rcParams["xtick.color"] (default: 'black'). The
same holds for . For instance, to set the ticks to light
grey and the tick labels to black, one can use the following code in a script:
3D Axes improvements
Errorbar method in 3D Axes
The errorbar function Axes.errorbar is ported into the 3D Axes framework in
its entirety, supporting features such as custom styling for error lines and
cap marks, control over errorbar spacing, upper and lower limit marks.
Stem plots in 3D Axes
Stem plots are now supported on 3D Axes. Much like 2D stems,
stem supports plotting the stems in various orientations:
Previously, properties of a 3D Collection that were used for 3D effects (e.g.,
colors were modified to produce depth shading) could not be changed after it
was created.
Now it is possible to modify all properties of 3D Collections at any time.
Panning in 3D Axes
Click and drag with the middle mouse button to pan 3D Axes.
Interactive tool improvements
New RangeSlider widget
widgets.RangeSlider allows for creating a slider that defines
a range rather than a single value.
The Slider UI widget now accepts arrays for valstep.
This generalizes the previous behavior by allowing the slider to snap to
arbitrary values.
Pausing and Resuming Animations
The animation.Animation.pause and animation.Animation.resume methods
allow you to pause and resume animations. These methods can be used as
callbacks for event listeners on UI elements so that your plots can have some
playback control UI.
Sphinx extensions
plot_directivecaption option
Captions were previously supported when using the plot_directive directive
with an external source file by specifying content:
Elements of a vector output can be individually set to rasterized, using the
rasterized keyword argument, or set_rasterized(). This can
be useful to reduce file sizes. For figures with multiple raster elements they
are now automatically merged into a smaller number of bitmaps where this will
not effect the visual output. For cases with many elements this can result in
significantly smaller file sizes.
To ensure this happens do not place vector elements between raster ones.
To inhibit this merging set Figure.suppressComposite to True.
Support raw/rgba frame format in FFMpegFileWriter
When using FFMpegFileWriter, the frame_format may now be set to "raw"
or "rgba", which may be slightly faster than an image format, as no
encoding/decoding need take place between Matplotlib and FFmpeg.
nbAgg/WebAgg support middle-click and double-click
Double click events are now supported by the nbAgg and WebAgg backends.
Formerly, WebAgg would report middle-click events as right clicks, but now
reports the correct button type.
nbAgg support binary communication
If the web browser and notebook support binary websockets, nbAgg will now use
them for slightly improved transfer of figure display.
Indexed color for PNG images in PDF files when possible
When PNG images have 256 colors or fewer, they are converted to indexed color
before saving them in a PDF. This can result in a significant reduction in file
size in some cases. This is particularly true for raster data that uses a
colormap but no interpolation, such as Healpy mollview plots. Currently, this
is only done for RGB images.
Improved font subsettings in PDF/PS
Font subsetting in PDF and PostScript has been re-written from the embedded
ttconv C code to Python. Some composite characters and outlines may have
changed slightly. This fixes ttc subsetting in PDF, and adds support for
subsetting of type 3 OTF fonts, resulting in smaller files (much smaller when
using CJK fonts), and avoids running into issues with type 42 embedding and
certain PDF readers such as Acrobat Reader.
Kerning added to strings in PDFs
As with text produced in the Agg backend (see the previous what's new
entry for examples), PDFs now include kerning in
text strings.
Fully-fractional HiDPI in QtAgg
Fully-fractional HiDPI (that is, HiDPI ratios that are not whole integers) was
added in Qt 5.14, and is now supported by the QtAgg backend when using this
version of Qt or newer.
Note that there are lines between the grid boundaries of the main plot which
are not the same transparency. The colorbar also shows these lines when a
transparency is added to the colormap because internally it uses pcolormesh to
draw the colorbar. With snapping on by default (below), the lines at the grid
boundaries disappear.
If the center of symmetry is different from 0, it can be set with the vcenter
argument. To manually set the range of CenteredNorm, use
the halfrange argument.