API Changes for 3.5.0#
Behaviour changes#
First argument to subplot_mosaic renamed#
Both Figure.subplot_mosaic, and pyplot.subplot_mosaic have had the
first positional argument renamed from layout to mosaic. As we have
consolidated the constrained_layout and tight_layout keyword arguments in
the Figure creation functions of pyplot into a single layout keyword
argument, the original subplot_mosaic argument name would collide.
As this API is provisional, we are changing this argument name with no deprecation period.
Axes children are no longer separated by type#
Formerly, axes.Axes children were separated by Artist type, into sublists
such as Axes.lines. For methods that produced multiple elements (such as
Axes.errorbar), though individual parts would have similar zorder, this
separation might cause them to be drawn at different times, causing
inconsistent results when overlapping other Artists.
Now, the children are no longer separated by type, and the sublist properties
are generated dynamically when accessed. Consequently, Artists will now always
appear in the correct sublist; e.g., if axes.Axes.add_line is called on a
Patch, it will appear in the Axes.patches sublist, not Axes.lines.
The Axes.add_* methods will now warn if passed an unexpected type.
Modification of the following sublists is still accepted, but deprecated:
Axes.artistsAxes.collectionsAxes.imagesAxes.linesAxes.patchesAxes.tablesAxes.texts
To remove an Artist, use its Artist.remove method. To add an Artist, use the
corresponding Axes.add_* method.
MatplotlibDeprecationWarning now subclasses DeprecationWarning#
Historically, it has not been possible to filter
MatplotlibDeprecationWarnings by checking for
DeprecationWarning, since we subclass UserWarning directly.
The decision to not subclass DeprecationWarning has to do with a decision
from core Python in the 2.x days to not show DeprecationWarnings to users.
However, there is now a more sophisticated filter in place (see
https://www.python.org/dev/peps/pep-0565/).
Users will now see MatplotlibDeprecationWarning only during
interactive sessions, and these can be silenced by the standard mechanism:
warnings.filterwarnings("ignore", category=DeprecationWarning)
Library authors must now enable DeprecationWarnings explicitly in order for
(non-interactive) CI/CD pipelines to report back these warnings, as is standard
for the rest of the Python ecosystem:
warnings.filterwarnings("always", DeprecationWarning)
Artist.set applies artist properties in the order in which they are given#
The change only affects the interaction between the color, edgecolor,
facecolor, and (for Collections) alpha properties: the color property
now needs to be passed first in order not to override the other properties.
This is consistent with e.g. Artist.update, which did not reorder the
properties passed to it.
pcolor(mesh) shading defaults to auto#
The shading keyword argument for Axes.pcolormesh and Axes.pcolor
default has been changed to 'auto'.
Passing Z(M, N), x(N), y(M) to pcolormesh with
shading='flat' will now raise a TypeError. Use shading='auto' or
shading='nearest' for x and y to be treated as cell centers, or
drop the last column and row of Z to get the old behaviour with
shading='flat'.
Colorbars now have pan and zoom functionality#
Interactive plots with colorbars can now be zoomed and panned on the colorbar
axis. This adjusts the vmin and vmax of the ScalarMappable associated
with the colorbar. This is currently only enabled for continuous norms. Norms
used with contourf and categoricals, such as BoundaryNorm and NoNorm,
have the interactive capability disabled by default. cb.ax.set_navigate() can be used to set whether a colorbar axes is interactive
or not.
Colorbar lines no longer clipped#
If a colorbar has lines added to it (e.g. for contour lines), these will no longer be clipped. This is an improvement for lines on the edge of the colorbar, but could lead to lines off the colorbar if the limits of the colorbar are changed.
Figure.suppressComposite now also controls compositing of Axes images#
The output of NonUniformImage and PcolorImage has changed#
Pixel-level differences may be observed in images generated using
NonUniformImage or PcolorImage, typically for pixels exactly at the
boundary between two data cells (no user-facing axes method currently generates
NonUniformImages, and only pcolorfast can generate PcolorImages).
These artists are also now slower, normally by ~1.5x but sometimes more (in
particular for NonUniformImage(interpolation="bilinear"). This slowdown
arises from fixing occasional floating point inaccuracies.
Change of the (default) legend handler for Line2D instances#
The default legend handler for Line2D instances (HandlerLine2D) now
consistently exposes all the attributes and methods related to the line marker
(#11358). This makes it easy to change the marker features after
instantiating a legend.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 3, 2], marker="s", label="Line", color="pink", mec="red", ms=8)
leg = ax.legend()
leg.legendHandles[0].set_color("lightgray")
leg.legendHandles[0].set_mec("black") # marker edge color
The former legend handler for Line2D objects has been renamed
HandlerLine2DCompound. To revert to the previous behaviour, one can use
import matplotlib.legend as mlegend
from matplotlib.legend_handler import HandlerLine2DCompound
from matplotlib.lines import Line2D
mlegend.Legend.update_default_handler_map({Line2D: HandlerLine2DCompound()})
Setting Line2D marker edge/face color to None use rcParams#
Line2D.set_markeredgecolor(None) and Line2D.set_markerfacecolor(None)
now set the line property using the corresponding rcParam
(rcParams["lines.markeredgecolor"] (default: 'auto') and rcParams["lines.markerfacecolor"] (default: 'auto')). This is
consistent with other Line2D property setters.
Default theta tick locations for wedge polar plots have changed#
For polar plots that don't cover a full circle, the default theta tick locations are now at multiples of 10°, 15°, 30°, 45°, 90°, rather than using values that mostly make sense for linear plots (20°, 25°, etc.).
axvspan now plots full wedges in polar plots#
... rather than triangles.
Convenience converter from Scale to Normalize now public#
Downstream libraries can take advantage of colors.make_norm_from_scale to
create a Normalize subclass directly from an existing scale.
Usually norms have a scale, and the advantage of having a ScaleBase
attached to a norm is to provide a scale, and associated tick locators and
formatters, for the colorbar.
ContourSet always use PathCollection#
In order to correct rendering issues with closed loops, the ContourSet now
creates a PathCollection instead of a LineCollection for line contours.
This type matches the artist used for filled contours.
This affects ContourSet itself and its subclasses, QuadContourSet
(returned by Axes.contour), and TriContourSet (returned by
Axes.tricontour).
hatch.SmallFilledCircles inherits from hatch.Circles#
The hatch.SmallFilledCircles class now inherits from hatch.Circles rather
than from hatch.SmallCircles.
hexbin with a log norm#
hexbin no longer (incorrectly) adds 1 to every bin value if a log
norm is being used.
Setting invalid rcParams["date.converter"] now raises ValueError#
Previously, invalid values passed to rcParams["date.converter"] (default: 'auto') would be ignored with
a UserWarning, but now raise ValueError.
Text and TextBox added parse_math option#
Text and TextBox objects now allow a parse_math keyword-only argument
which controls whether math should be parsed from the displayed string. If
True, the string will be parsed as a math text object. If False, the string
will be considered a literal and no parsing will occur.
For Text, this argument defaults to True. For TextBox this argument
defaults to False.
Type1Font objects now decrypt the encrypted part#
Type 1 fonts have a large part of their code encrypted as an obsolete
copy-protection measure. This part is now available decrypted as the
decrypted attribute of matplotlib.type1font.Type1Font. This decrypted
data is not yet parsed, but this is a prerequisite for implementing subsetting.
3D contourf polygons placed between levels#
The polygons used in a 3D contourf plot are now
placed halfway between the contour levels, as each polygon represents the
location of values that lie between two levels.
AxesDivider now defaults to rcParams-specified pads#
AxesDivider.append_axes, AxesDivider.new_horizontal, and
AxesDivider.new_vertical now default to paddings specified by
rcParams["figure.subplot.wspace"] (default: 0.2) and rcParams["figure.subplot.hspace"] (default: 0.2) rather than zero.
Deprecations#
Discouraged: Figure parameters tight_layout and constrained_layout#
The Figure parameters tight_layout and constrained_layout are
triggering competing layout mechanisms and thus should not be used together.
To make the API clearer, we've merged them under the new parameter layout
with values 'constrained' (equal to constrained_layout=True), 'tight'
(equal to tight_layout=True). If given, layout takes precedence.
The use of tight_layout and constrained_layout is discouraged in favor of layout. However, these parameters will stay available for backward compatibility.
Modification of Axes children sublists#
See Axes children are no longer separated by type for more information; modification of the following sublists is deprecated:
Axes.artistsAxes.collectionsAxes.imagesAxes.linesAxes.patchesAxes.tablesAxes.texts
To remove an Artist, use its Artist.remove method. To add an Artist, use the
corresponding Axes.add_* method.
Passing incorrect types to Axes.add_* methods#
The following Axes.add_* methods will now warn if passed an unexpected
type. See their documentation for the types they expect.
Discouraged: plot_date#
The use of plot_date is discouraged. This method exists for historic
reasons and may be deprecated in the future.
datetime-like data should directly be plotted usingplot.If you need to plot plain numeric data as Matplotlib date format or need to set a timezone, call
ax.xaxis.axis_date/ax.yaxis.axis_datebeforeplot. SeeAxis.axis_date.
epoch2num and num2epoch are deprecated#
These methods convert from unix timestamps to matplotlib floats, but are not
used internally to matplotlib, and should not be needed by end users. To
convert a unix timestamp to datetime, simply use
datetime.datetime.utcfromtimestamp, or to use NumPy datetime64
dt = np.datetime64(e*1e6, 'us').
Auto-removal of grids by pcolor and pcolormesh#
pcolor and pcolormesh currently remove any visible axes major
grid. This behavior is deprecated; please explicitly call ax.grid(False) to
remove the grid.
The first parameter of Axes.grid and Axis.grid has been renamed to visible#
The parameter was previously named b. This deprecation only matters if that
parameter was passed using a keyword argument, e.g. grid(b=False).
Unification and cleanup of Selector widget API#
The API for Selector widgets has been unified to use:
props for the properties of the Artist representing the selection.
handle_props for the Artists representing handles for modifying the selection.
grab_range for the maximal tolerance to grab a handle with the mouse.
Additionally, several internal parameters and attribute have been deprecated with the intention of keeping them private.
RectangleSelector and EllipseSelector#
The drawtype keyword argument to RectangleSelector is
deprecated. In the future the only behaviour will be the default behaviour of
drawtype='box'.
Support for drawtype=line will be removed altogether as it is not clear
which points are within and outside a selector that is just a line. As a
result, the lineprops keyword argument to
RectangleSelector is also deprecated.
To retain the behaviour of drawtype='none', use rectprops={'visible':
False} to make the drawn Rectangle invisible.
Cleaned up attributes and arguments are:
The
active_handleattribute has been privatized and deprecated.The
drawtypeattribute has been privatized and deprecated.The
eventpressattribute has been privatized and deprecated.The
eventreleaseattribute has been privatized and deprecated.The
interactiveattribute has been privatized and deprecated.The marker_props argument is deprecated, use handle_props instead.
The maxdist argument is deprecated, use grab_range instead.
The rectprops argument is deprecated, use props instead.
The
rectpropsattribute has been privatized and deprecated.The
stateattribute has been privatized and deprecated.The
to_drawattribute has been privatized and deprecated.
PolygonSelector#
The line attribute is deprecated. If you want to change the selector artist properties, use the
set_propsorset_handle_propsmethods.The lineprops argument is deprecated, use props instead.
The markerprops argument is deprecated, use handle_props instead.
The maxdist argument and attribute is deprecated, use grab_range instead.
The vertex_select_radius argument and attribute is deprecated, use grab_range instead.
SpanSelector#
The
active_handleattribute has been privatized and deprecated.The
eventpressattribute has been privatized and deprecated.The
eventreleaseattribute has been privatized and deprecated.The maxdist argument and attribute is deprecated, use grab_range instead.
The
pressvattribute has been privatized and deprecated.The
prevattribute has been privatized and deprecated.The
rectattribute has been privatized and deprecated.The rectprops argument is deprecated, use props instead.
The
rectpropsattribute has been privatized and deprecated.The span_stays argument is deprecated, use the interactive argument instead.
The
span_staysattribute has been privatized and deprecated.The
stateattribute has been privatized and deprecated.
LassoSelector#
The lineprops argument is deprecated, use props instead.
The
onpressandonreleasemethods are deprecated. They are straight aliases forpressandrelease.
ConversionInterface.convert no longer needs to accept unitless values#
Previously, custom subclasses of units.ConversionInterface needed to
implement a convert method that not only accepted instances of the unit,
but also unitless values (which are passed through as is). This is no longer
the case (convert is never called with a unitless value), and such support
in StrCategoryConverter is deprecated. Likewise, the
.ConversionInterface.is_numlike helper is deprecated.
Consider calling Axis.convert_units instead, which still supports unitless
values.
Locator and Formatter wrapper methods#
The set_view_interval, set_data_interval and set_bounds methods of
Locators and Formatters (and their common base class, TickHelper) are
deprecated. Directly manipulate the view and data intervals on the underlying
axis instead.
Unused positional parameters to print_<fmt> methods#
None of the print_<fmt> methods implemented by canvas subclasses used
positional arguments other that the first (the output filename or file-like),
so these extra parameters are deprecated.
QuadMesh signature#
The QuadMesh signature
def __init__(meshWidth, meshHeight, coordinates,
antialiased=True, shading='flat', **kwargs)
is deprecated and replaced by the new signature
def __init__(coordinates, *, antialiased=True, shading='flat', **kwargs)
In particular:
The coordinates argument must now be a (M, N, 2) array-like. Previously, the grid shape was separately specified as (meshHeight + 1, meshWidth + 1) and coordinates could be an array-like of any shape with M * N * 2 elements.
All parameters except coordinates are keyword-only now.
rcParams will no longer cast inputs to str#
After a deprecation period, rcParams that expect a (non-pathlike) str will no
longer cast non-str inputs using str. This will avoid confusing errors in
subsequent code if e.g. a list input gets implicitly cast to a str.
Case-insensitive scales#
Previously, scales could be set case-insensitively (e.g.,
set_xscale("LoG")). This is deprecated; all builtin scales use lowercase
names.
Interactive cursor details#
Setting a mouse cursor on a window has been moved from the toolbar to the canvas. Consequently, several implementation details on toolbars and within backends have been deprecated.
backend_tools.SetCursorBase and subclasses#
backend_tools.SetCursorBase was subclassed to provide backend-specific
implementations of set_cursor. As that is now deprecated, the subclassing
is no longer necessary. Consequently, the following subclasses are also
deprecated:
matplotlib.backends.backend_gtk3.SetCursorGTK3matplotlib.backends.backend_qt5.SetCursorQtmatplotlib.backends._backend_tk.SetCursorTkmatplotlib.backends.backend_wx.SetCursorWx
Instead, use the backend_tools.ToolSetCursor class.
cursord in GTK, Qt, and wx backends#
The backend_gtk3.cursord, backend_qt.cursord, and
backend_wx.cursord dictionaries are deprecated. This makes the GTK module
importable on headless environments.
Miscellaneous deprecations#
is_urlandURL_REGEXare deprecated. (They were previously defined in the toplevelmatplotlibmodule.)The
ArrowStyle.beginarrowandArrowStyle.endarrowattributes are deprecated; use thearrowattribute to define the desired heads and tails of the arrow.backend_pgf.LatexManager.str_cacheis deprecated.backends.qt_compat.ETSandbackends.qt_compat.QT_RC_MAJOR_VERSIONare deprecated, with no replacement.The
blocking_inputmodule has been deprecated. Instead, usecanvas.start_event_loop()andcanvas.stop_event_loop()while connecting event callbacks as needed.cbook.report_memoryis deprecated; usepsutil.virtual_memoryinstead.cm.LUTSIZEis deprecated. UsercParams["image.lut"](default:256) instead. This value only affects colormap quantization levels for default colormaps generated at module import time.Collection.__init__previously ignored transOffset without offsets also being specified. In the future, transOffset will begin having an effect regardless of offsets. In the meantime, if you wish to set transOffset, callCollection.set_offset_transformexplicitly.Colorbar.patchis deprecated; this attribute is not correctly updated anymore.ContourLabeler.get_label_widthis deprecated.dviread.PsfontsMapnow raises LookupError instead of KeyError for missing fonts.Dvi.baselineis deprecated (with no replacement).The format parameter of
dviread.find_tex_fileis deprecated (with no replacement).FancyArrowPatch.get_path_in_displaycoordandConnectionPath.get_path_in_displaycoordare deprecated. The path in display coordinates can still be obtained, as for other patches, usingpatch.get_transform().transform_path(patch.get_path()).The
font_manager.win32InstalledFontsandfont_manager.get_fontconfig_fontshelper functions have been deprecated.All parameters of
imshowstarting from aspect will become keyword-only.QuadMesh.convert_mesh_to_pathsandQuadMesh.convert_mesh_to_trianglesare deprecated.QuadMesh.get_paths()can be used as an alternative for the former; there is no replacement for the latter.ScalarMappable.callbacksSMis deprecated. UseScalarMappable.callbacksinstead.streamplot.get_integratoris deprecated.style.core.STYLE_FILE_PATTERN,style.core.load_base_library, andstyle.core.iter_user_librariesare deprecated.SubplotParams.validateis deprecated. UseSubplotParams.updateto changeSubplotParamswhile always keeping it in a valid state.The
grey_arrayd,font_family,font_families, andfont_infoattributes ofTexManagerare deprecated.Text.get_prop_tupis deprecated with no replacements (because theTextclass cannot know whether a backend needs to update cache e.g. when the text's color changes).Tick.apply_tickdirdidn't actually update the tick markers on the existing Line2D objects used to draw the ticks and is deprecated; useAxis.set_tick_paramsinstead.tight_layout.auto_adjust_subplotparsis deprecated.The
grid_infoattribute ofaxisartistclasses has been deprecated.axisartist.clip_pathis deprecated with no replacement.axes_grid1.axes_grid.CbarAxesandaxes_grid1.axisartist.CbarAxesare deprecated (they are now dynamically generated based on the owning axes class).The
axes_grid1.Divider.get_vsize_hsizeandaxes_grid1.Grid.get_vsize_hsizemethods are deprecated. Copy their implementations if needed.AxesDivider.append_axes(..., add_to_figure=False)is deprecated. Useax.remove()to remove the Axes from the figure if needed.FixedAxisArtistHelper.change_tick_coordis deprecated with no replacement.floating_axes.GridHelperCurveLinear.get_boundaryis deprecated, with no replacement.ParasiteAxesBase.get_images_artistshas been deprecated.The "units finalize" signal (previously emitted by Axis instances) is deprecated. Connect to "units" instead.
Passing formatting parameters positionally to
stem()is deprecated
plot_directive deprecations#
The :encoding: option to .. plot directive has had no effect since
Matplotlib 1.3.1, and is now deprecated.
The following helpers in matplotlib.sphinxext.plot_directive are deprecated:
unescape_doctest(usedoctest.script_from_examplesinstead),split_code_at_show,run_code.
Testing support#
matplotlib.test() is deprecated#
Run tests using pytest from the commandline instead. The variable
matplotlib.default_test_modules is only used for matplotlib.test() and
is thus deprecated as well.
To test an installed copy, be sure to specify both matplotlib and
mpl_toolkits with --pyargs:
pytest --pyargs matplotlib.tests mpl_toolkits.tests
See Testing for more details.
Unused pytest fixtures and markers#
The fixture matplotlib.testing.conftest.mpl_image_comparison_parameters is
not used internally by Matplotlib. If you use this please copy it into your
code base.
The @pytest.mark.style marker is deprecated; use @mpl.style.context,
which has the same effect.
Support for nx1 = None or ny1 = None in AxesLocator and Divider.locate#
In axes_grid1.axes_divider, various internal APIs will stop supporting
passing nx1 = None or ny1 = None to mean nx + 1 or ny + 1, in
preparation for a possible future API which allows indexing and slicing of
dividers (possibly divider[a:b] == divider.new_locator(a, b), but also
divider[a:] == divider.new_locator(a, <end>)). The user-facing
Divider.new_locator API is unaffected -- it correctly normalizes nx1 =
None and ny1 = None as needed.
Removals#
The following deprecated APIs have been removed:
Removed behaviour#
Stricter validation of function parameters#
Calling
Figure.add_axeswith no arguments will raise an error. Adding a free-floating axes needs a position rectangle. If you want a figure-filling single axes, useFigure.add_subplotinstead.Figure.add_subplotvalidates its inputs; in particular, foradd_subplot(rows, cols, index), all parameters must be integral. Previously strings and floats were accepted and converted to int.Passing None as the which argument to
autofmt_xdateis no longer supported; use its more explicit synonym,which="major", instead.Setting the orientation of an
eventplot()orEventCollectionto "none" or None is no longer supported; set it to "horizontal" instead. Moreover, the two orientations ("horizontal" and "vertical") are now case-sensitive.Passing parameters norm and vmin/vmax simultaneously to functions using colormapping such as
scatter()andimshow()is no longer supported. Instead ofnorm=LogNorm(), vmin=min_val, vmax=max_valpassnorm=LogNorm(min_val, max_val). vmin and vmax should only be used without setting norm.Passing None as either the radius or startangle arguments of an
Axes.pieis no longer accepted; use the explicit defaults of 1 and 0, respectively, instead.Passing None as the normalize argument of
Axes.pie(the former default) is no longer accepted, and the pie will always be normalized by default. If you wish to plot an incomplete pie, explicitly passnormalize=False.Support for passing None to
subplot_class_factoryhas been removed. Explicitly pass in the baseAxesclass instead.Passing multiple keys as a single comma-separated string or multiple arguments to
ToolManager.update_keymapis no longer supported; pass keys as a list of strings instead.Passing the dash offset as None is no longer accepted, as this was never universally implemented, e.g. for vector output. Set the offset to 0 instead.
Setting a custom method overriding
Artist.containsusingArtist.set_containshas been removed, as hasArtist.get_contains. There is no replacement, but you may still customize pick events usingArtist.set_picker.semilogx,semilogy,loglog,LogScale, andSymmetricalLogScaleused to take keyword arguments that depends on the axis orientation ("basex" vs "basey", "subsx" vs "subsy", "nonposx" vs "nonposy"); these parameter names have been removed in favor of "base", "subs", "nonpositive". This removal also affects e.g.ax.set_yscale("log", basey=...)which must now be spelledax.set_yscale("log", base=...).The change from "nonpos" to "nonpositive" also affects
LogTransform,InvertedLogTransform,SymmetricalLogTransform, etc.To use different bases for the x-axis and y-axis of a
loglogplot, use e.g.ax.set_xscale("log", base=10); ax.set_yscale("log", base=2).Passing None, or no argument, to
parasite_axes_class_factory,parasite_axes_auxtrans_class_factory,host_axes_class_factoryis no longer accepted; pass an explicit base class instead.
Case-sensitivity is now enforced more#
Upper or mixed-case property names are no longer normalized to lowercase in
Artist.setandArtist.update. This allows one to pass names such as patchA or UVC.Case-insensitive capstyles and joinstyles are no longer lower-cased; please pass capstyles ("miter", "round", "bevel") and joinstyles ("butt", "round", "projecting") as lowercase.
Saving metadata in PDF with the PGF backend no longer changes keys to lowercase. Only the canonically cased keys listed in the PDF specification (and the
PdfPagesdocumentation) are accepted.
No implicit initialization of Tick attributes#
The Tick constructor no longer initializes the attributes tick1line,
tick2line, gridline, label1, and label2 via _get_tick1line,
_get_tick2line, _get_gridline, _get_text1, and _get_text2.
Please directly set the attribute in the subclass' __init__ instead.
Removal of old file mode flag#
Flags containing "U" passed to cbook.to_filehandle and cbook.open_file_cm
are no longer accepted. This is consistent with their removal from open in
Python 3.9.
The TTFPATH and AFMPATH environment variables#
Support for the (undocumented) TTFPATH and AFMPATH environment
variables has been removed. Register additional fonts using
matplotlib.font_manager.fontManager.addfont().
Modules#
matplotlib.backends.qt_editor.formsubplottool; usematplotlib.backends.backend_qt.SubplotToolQtinstead.matplotlib.compatmatplotlib.ttconvThe Qt4-based backends,
qt4aggandqt4cairo, have been removed. Qt4 has reached its end-of-life in 2015 and there are no releases of either PyQt4 or PySide for recent versions of Python. Please use one of the Qt5 or Qt6 backends.
Classes, methods and attributes#
The following module-level classes/variables have been removed:
backend_bases.StatusbarBaseand all its subclasses, andStatusBarWx; messages are displayed in the toolbarbackend_pgf.GraphicsContextPgfMODIFIER_KEYS,SUPER,ALT,CTRL, andSHIFTofmatplotlib.backends.backend_qt5aggandmatplotlib.backends.backend_qt5cairobackend_wx.DEBUG_MSGdviread.EncodingFil,Fill,Filll,NegFil,NegFill,NegFilll, andSsGluefrommathtext; directly construct glue instances withGlue("fil"), etc.mathtext.GlueSpecOldScalarFormatter,IndexFormatterandIndexDateFormatter; useFuncFormatterinsteadOldAutoLocatorAVConvBase,AVConvWriterandAVConvFileWriter. Debian 8 (2015, EOL 06/2020) and Ubuntu 14.04 (EOL 04/2019) were the last versions of Debian and Ubuntu to ship avconv. It remains possible to force the use of avconv by using the FFmpeg-based writers withrcParams["animation.ffmpeg_path"](default:'ffmpeg') set to "avconv".matplotlib.axes._subplots._subplot_classesaxes_grid1.axes_rgb.RGBAxesBase; useRGBAxesinstead
The following class attributes have been removed:
backend_pgf.LatexManager.latex_stdin_utf8backend_pgf.PdfPages.metadataContourSet.axandQuiver.ax; useContourSet.axesorQuiver.axesas with other artistsDateFormatter.illegal_sdates.YearLocator.replaced;YearLocatoris now a subclass ofRRuleLocator, and the attributeYearLocator.replacedhas been removed. For tick locations that required modifying this, a custom rrule andRRuleLocatorcan be used instead.FigureManagerBase.statusbar; messages are displayed in the toolbarFileMovieWriter.clear_tempmathtext.Glue.glue_subtypeMovieWriter.args_key,MovieWriter.exec_key, andHTMLWriter.args_keyNavigationToolbar2QT.basedir; the base directory to the icons isos.path.join(mpl.get_data_path(), "images")NavigationToolbar2QT.ctxNavigationToolbar2QT.parent; to access the parent window, usetoolbar.canvas.parent()ortoolbar.parent()prevZoomRect,retinaFix,savedRetinaImage,wxoverlay,zoomAxes,zoomStartX, andzoomStartYattributes ofNavigationToolbar2WxNonUniformImage.is_grayscale,PcolorImage.is_grayscale, for consistency withAxesImage.is_grayscale. (Note that previously, these attributes were only available after rendering the image).RendererCairo.fontweights,RendererCairo.fontanglesused_charactersofRendererPdf,PdfFile, andRendererPSLogScale.LogTransform,LogScale.InvertedLogTransform,SymmetricalScale.SymmetricalTransform, andSymmetricalScale.InvertedSymmetricalTransform; directly access the transform classes frommatplotlib.scalecachedir,rgba_arrayd,serif,sans_serif,cursive, andmonospaceattributes ofTexManageraxleft,axright,axbottom,axtop,axwspace, andaxhspaceattributes ofwidgets.SubplotTool; access theaxattribute of the corresponding sliderwidgets.TextBox.params_to_disableangle_helper.LocatorBase.den; it has been renamed to nbinsaxes_grid.CbarAxesBase.cbidandaxes_grid.CbarAxesBase.locator; usemappable.colorbar_cidorcolorbar.locatorinstead
The following class methods have been removed:
Axes.update_datalim_bounds; useax.dataLim.set(Bbox.union([ax.dataLim, bounds]))panandzoommethods ofAxisandLocatorhave been removed; panning and zooming are now implemented using thestart_pan,drag_pan, andend_panmethods ofAxes.BboxBase.inverse_transformed; callBboxBase.transformedon theinverted()transformCollection.set_offset_positionandCollection.get_offset_positionhave been removed; theoffset_positionof theCollectionclass is now "screen"Colorbar.on_mappable_changedandColorbar.update_bruteforce; useColorbar.update_normal()insteaddocstring.Substitution.from_paramshas been removed; directly assign toparamsofdocstring.SubstitutioninsteadDraggableBase.artist_picker; set the artist's picker insteadDraggableBase.on_motion_blit; useDraggableBase.on_motioninsteadFigureCanvasGTK3._renderer_initLocator.refresh()and the associated helper methodsNavigationToolbar2.draw()andToolViewsPositions.refresh_locators()track_charactersandmerge_used_charactersofRendererPdf,PdfFile, andRendererPSRendererWx.get_gcSubplotSpec.get_rows_columns; use theGridSpec.nrows,GridSpec.ncols,SubplotSpec.rowspan, andSubplotSpec.colspanproperties instead.ScalarMappable.update_dict,ScalarMappable.add_checker(), andScalarMappable.check_update(); register a callback inScalarMappable.callbacksto be notified of updatesTexManager.make_tex_previewandTexManager.make_dvi_previewfuncleft,funcright,funcbottom,functop,funcwspace, andfunchspacemethods ofwidgets.SubplotToolaxes_grid1.axes_rgb.RGBAxes.add_RGB_to_figureaxisartist.axis_artist.AxisArtist.dpi_transformaxisartist.grid_finder.MaxNLocator.set_factorandaxisartist.grid_finder.FixedLocator.set_factor; the factor is always 1 now
Functions#
bezier.make_path_regularhas been removed; usePath.cleaned()(orPath.cleaned(curves=True), etc.) instead, but note that these methods add aSTOPcode at the end of the path.bezier.concatenate_pathshas been removed; usePath.make_compound_path()instead.cbook.local_over_kwdicthas been removed; usecbook.normalize_kwargsinstead.qt_compat.is_pyqt5has been removed due to the release of PyQt6. The Qt version can be checked usingQtCore.qVersion().testing.compare.make_external_conversion_commandhas been removed.axes_grid1.axes_rgb.imshow_rgbhas been removed; useimshow(np.dstack([r, g, b]))instead.
Arguments#
The s parameter to
Axes.annotateandpyplot.annotateis no longer supported; use the new name text.The inframe parameter to
matplotlib.axes.Axes.drawhas been removed; useAxes.redraw_in_frameinstead.The required, forbidden and allowed parameters of
cbook.normalize_kwargshave been removed.The ismath parameter of the
draw_texmethod of all renderer classes has been removed (as a call todraw_tex— not to be confused withdraw_text! — means that the entire string should be passed to theusetexmachinery anyways). Likewise, the text machinery will no longer pass the ismath parameter when callingdraw_tex(this should only matter for backend implementers).The quality, optimize, and progressive parameters of
Figure.savefig(which only affected JPEG output) have been removed, as well as from the correspondingprint_jpgmethods. JPEG output options can be set by directly passing the relevant parameters in pil_kwargs.The clear_temp parameter of
FileMovieWriterhas been removed; files placed in a temporary directory (usingframe_prefix=None, the default) will be cleared; files placed elsewhere will not.The copy parameter of
mathtext.Gluehas been removed.The quantize parameter of
Path.cleaned()has been removed.The dummy parameter of
RendererPgfhas been removed.The props parameter of
Shadowhas been removed; use keyword arguments instead.The recursionlimit parameter of
matplotlib.testhas been removed.The label parameter of
Tickhas no effect and has been removed.MaxNLocatorno longer accepts a positional parameter and the keyword argument nbins simultaneously because they specify the same quantity.The add_all parameter to
axes_grid.Grid,axes_grid.ImageGrid,axes_rgb.make_rgb_axes, andaxes_rgb.RGBAxeshave been removed; the APIs always behave as ifadd_all=True.The den parameter of
axisartist.angle_helper.LocatorBasehas been removed; use nbins instead.The s keyword argument to
AnnotationBbox.get_fontsizehas no effect and has been removed.The offset_position keyword argument of the
Collectionclass has been removed; theoffset_positionnow "screen".Arbitrary keyword arguments to
StreamplotSethave no effect and have been removed.The fontdict and minor parameters of
Axes.set_xticklabels/Axes.set_yticklabelsare now keyword-only.All parameters of
Figure.subplotsexcept nrows and ncols are now keyword-only; this avoids typing e.g.subplots(1, 1, 1)when meaningsubplot(1, 1, 1), but actually gettingsubplots(1, 1, sharex=1).All parameters of
pyplot.tight_layoutare now keyword-only, to be consistent withFigure.tight_layout.ColorbarBaseonly takes a single positional argument now, theAxesto create it in, with all other options required to be keyword arguments. The warning for keyword arguments that were overridden by the mappable is now removed.Omitting the renderer parameter to
matplotlib.axes.Axes.drawis no longer supported; useaxes.draw_artist(axes)instead.Passing
ismath="TeX!"toRendererAgg.get_text_width_height_descentis no longer supported; passismath="TeX"instead,Changes to the signature of the
matplotlib.axes.Axes.drawmethod make it consistent with all other artists; thus additional parameters toArtist.drawhave also been removed.
rcParams#
The
animation.avconv_pathandanimation.avconv_argsrcParams have been removed.The
animation.html_argsrcParam has been removed.The
keymap.all_axesrcParam has been removed.The
mathtext.fallback_to_cmrcParam has been removed. UsercParams["mathtext.fallback"](default:'cm') instead.The
savefig.jpeg_qualityrcParam has been removed.The
text.latex.previewrcParam has been removed.The following deprecated rcParams validators, defined in
rcsetup, have been removed:validate_alignmentvalidate_axes_titlelocationvalidate_axis_locatorvalidate_bool_maybe_nonevalidate_fontsetvalidate_grid_axisvalidate_hintingvalidate_legend_locvalidate_mathtext_defaultvalidate_movie_frame_fmtvalidate_movie_html_fmtvalidate_movie_writervalidate_nseq_floatvalidate_nseq_intvalidate_orientationvalidate_pgf_texsystemvalidate_ps_papersizevalidate_svg_fonttypevalidate_toolbarvalidate_webagg_address
Some rcParam validation has become stricter:
rcParams["axes.axisbelow"](default:'line') no longer accepts strings starting with "line" (case-insensitive) as "line"; use "line" (case-sensitive) instead.rcParams["text.latex.preamble"](default:'') andpdf.preambleno longer accept non-string values.All
*.linestylercParams no longer acceptoffset = None; set the offset to 0 instead.
Development changes#
Increase to minimum supported versions of dependencies#
For Matplotlib 3.5, the minimum supported versions and some optional dependencies are being bumped:
Dependency |
min in mpl3.4 |
min in mpl3.5 |
|---|---|---|
NumPy |
1.16 |
1.17 |
Tk (optional) |
8.3 |
8.4 |
This is consistent with our Dependency version policy and NEP29
New wheel architectures#
Wheels have been added for:
Python 3.10
PyPy 3.7
macOS on Apple Silicon (both arm64 and universal2)
New build dependencies#
Versioning has been switched from bundled versioneer to setuptools-scm using the
release-branch-semver version scheme. The latter is well-maintained, but
may require slight modification to packaging scripts.
The setuptools-scm-git-archive plugin is also used for consistent version export.
Data directory is no longer optional#
Historically, the mpl-data directory has been optional (example files were
unnecessary, and fonts could be deleted if a suitable dependency on a system
font were provided). Though example files are still optional, they have been
substantially pared down, and we now consider the directory to be required.
Specifically, the matplotlibrc file found there is used for runtime
verifications and must exist. Packagers may still symlink fonts to system
versions if needed.
New runtime dependencies#
fontTools for type 42 subsetting#
A new dependency fontTools is integrated into Matplotlib 3.5. It is designed to be used with PS/EPS and PDF documents; and handles Type 42 font subsetting.
Underscore support in LaTeX#
The underscore package is now a requirement to improve support for underscores in LaTeX.
This is consistent with our Dependency version policy.
Matplotlib-specific build options moved from setup.cfg to mplsetup.cfg#
In order to avoid conflicting with the use of setup.cfg by
setuptools, the Matplotlib-specific build options have moved from
setup.cfg to mplsetup.cfg. The setup.cfg.template has been
correspondingly been renamed to mplsetup.cfg.template.
Note that the path to this configuration file can still be set via the MPLSETUPCFG
environment variable, which allows one to keep using the same file before and after this
change.