diff --git a/lib/matplotlib/_constrained_layout.py b/lib/matplotlib/_constrained_layout.py index 7ced20b3cf50..ec01448c524e 100644 --- a/lib/matplotlib/_constrained_layout.py +++ b/lib/matplotlib/_constrained_layout.py @@ -17,7 +17,7 @@ import numpy as np -import matplotlib.cbook as cbook +from matplotlib import _api import matplotlib.transforms as mtransforms _log = logging.getLogger(__name__) @@ -94,9 +94,9 @@ def do_constrained_layout(fig, renderer, h_pad, w_pad, gss.add(gs) gss = list(gss) if len(gss) == 0: - cbook._warn_external('There are no gridspecs with layoutgrids. ' - 'Possibly did not call parent GridSpec with the' - ' "figure" keyword') + _api.warn_external('There are no gridspecs with layoutgrids. ' + 'Possibly did not call parent GridSpec with the' + ' "figure" keyword') for _ in range(2): # do the algorithm twice. This has to be done because decorations @@ -122,9 +122,9 @@ def do_constrained_layout(fig, renderer, h_pad, w_pad, _reposition_axes(fig, renderer, h_pad=h_pad, w_pad=w_pad, hspace=hspace, wspace=wspace) else: - cbook._warn_external('constrained_layout not applied because ' - 'axes sizes collapsed to zero. Try making ' - 'figure larger or axes decorations smaller.') + _api.warn_external('constrained_layout not applied because ' + 'axes sizes collapsed to zero. Try making ' + 'figure larger or axes decorations smaller.') _reset_margins(fig) diff --git a/lib/matplotlib/animation.py b/lib/matplotlib/animation.py index 3bf6cc1b601f..16f509e98684 100644 --- a/lib/matplotlib/animation.py +++ b/lib/matplotlib/animation.py @@ -475,7 +475,7 @@ def frame_format(self, frame_format): if frame_format in self.supported_formats: self._frame_format = frame_format else: - cbook._warn_external( + _api.warn_external( f"Ignoring file format {frame_format!r} which is not " f"supported by {type(self).__name__}; using " f"{self.supported_formats[0]} instead.") diff --git a/lib/matplotlib/artist.py b/lib/matplotlib/artist.py index a3929e36f042..0a238267b20d 100644 --- a/lib/matplotlib/artist.py +++ b/lib/matplotlib/artist.py @@ -901,8 +901,7 @@ def set_rasterized(self, rasterized): rasterized : bool """ if rasterized and not hasattr(self.draw, "_supports_rasterization"): - cbook._warn_external( - "Rasterization of '%s' will be ignored" % self) + _api.warn_external(f"Rasterization of '{self}' will be ignored") self._rasterized = rasterized diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index 40c5a7dc95bc..40959b06fe64 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -4722,9 +4722,8 @@ def reduce_C_function(C: array) -> float # Set normalizer if bins is 'log' if bins == 'log': if norm is not None: - cbook._warn_external("Only one of 'bins' and 'norm' " - "arguments can be supplied, ignoring " - "bins={}".format(bins)) + _api.warn_external("Only one of 'bins' and 'norm' arguments " + f"can be supplied, ignoring bins={bins}") else: norm = mcolors.LogNorm() bins = None @@ -5436,9 +5435,9 @@ def _pcolorargs(self, funcname, *args, shading='flat', **kwargs): try: _api.check_in_list(_valid_shading, shading=shading) except ValueError as err: - cbook._warn_external(f"shading value '{shading}' not in list of " - f"valid values {_valid_shading}. Setting " - "shading='auto'.") + _api.warn_external(f"shading value '{shading}' not in list of " + f"valid values {_valid_shading}. Setting " + "shading='auto'.") shading = 'auto' if len(args) == 1: @@ -5523,7 +5522,7 @@ def _interp_grid(X): if np.shape(X)[1] > 1: dX = np.diff(X, axis=1)/2. if not (np.all(dX >= 0) or np.all(dX <= 0)): - cbook._warn_external( + _api.warn_external( f"The input coordinates to {funcname} are " "interpreted as cell centers, but are not " "monotonically increasing or decreasing. " diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index b5e3fc7ac3cd..f2106fd00592 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -268,7 +268,7 @@ def __call__(self, *args, data=None, **kwargs): label_namer_idx = 1 else: if replaced[1] is not args[1]: # case 2a) - cbook._warn_external( + _api.warn_external( f"Second argument {args[1]!r} is ambiguous: could " f"be a format string but is in 'data'; using as " f"data. If it was intended as data, set the " @@ -2456,7 +2456,7 @@ def margins(self, *margins, x=None, y=None, tight=True): if x is None and y is None: if tight is not True: - cbook._warn_external(f'ignoring tight={tight!r} in get mode') + _api.warn_external(f'ignoring tight={tight!r} in get mode') return self._xmargin, self._ymargin if tight is not None: @@ -3442,19 +3442,19 @@ def set_xlim(self, left=None, right=None, emit=True, auto=False, # so only grab the limits if we really need them. old_left, old_right = self.get_xlim() if left <= 0: - cbook._warn_external( + _api.warn_external( 'Attempted to set non-positive left xlim on a ' 'log-scaled axis.\n' 'Invalid limit will be ignored.') left = old_left if right <= 0: - cbook._warn_external( + _api.warn_external( 'Attempted to set non-positive right xlim on a ' 'log-scaled axis.\n' 'Invalid limit will be ignored.') right = old_right if left == right: - cbook._warn_external( + _api.warn_external( f"Attempting to set identical left == right == {left} results " f"in singular transformations; automatically expanding.") reverse = left > right @@ -3768,19 +3768,19 @@ def set_ylim(self, bottom=None, top=None, emit=True, auto=False, # so only grab the limits if we really need them. old_bottom, old_top = self.get_ylim() if bottom <= 0: - cbook._warn_external( + _api.warn_external( 'Attempted to set non-positive bottom ylim on a ' 'log-scaled axis.\n' 'Invalid limit will be ignored.') bottom = old_bottom if top <= 0: - cbook._warn_external( + _api.warn_external( 'Attempted to set non-positive top ylim on a ' 'log-scaled axis.\n' 'Invalid limit will be ignored.') top = old_top if bottom == top: - cbook._warn_external( + _api.warn_external( f"Attempting to set identical bottom == top == {bottom} " f"results in singular transformations; automatically " f"expanding.") @@ -4067,7 +4067,7 @@ def _set_view_from_bbox(self, bbox, direction='in', xzc + xwidth/2./scl, yzc + ywidth/2./scl] elif len(bbox) != 4: # should be len 3 or 4 but nothing else - cbook._warn_external( + _api.warn_external( "Warning in _set_view_from_bbox: bounding box is not a tuple " "of length 3 or 4. Ignoring the view change.") return @@ -4211,7 +4211,7 @@ def format_deltas(key, dx, dy): result = (mtransforms.Bbox(newpoints) .transformed(p.trans_inverse)) except OverflowError: - cbook._warn_external('Overflow while panning') + _api.warn_external('Overflow while panning') return else: return diff --git a/lib/matplotlib/axes/_secondary_axes.py b/lib/matplotlib/axes/_secondary_axes.py index d59b6ab8953d..49c968499fe6 100644 --- a/lib/matplotlib/axes/_secondary_axes.py +++ b/lib/matplotlib/axes/_secondary_axes.py @@ -1,7 +1,6 @@ import numpy as np from matplotlib import _api -import matplotlib.cbook as cbook import matplotlib.docstring as docstring import matplotlib.ticker as mticker from matplotlib.axes._base import _AxesBase, _TransformedBoundsLocator @@ -246,7 +245,7 @@ def set_aspect(self, *args, **kwargs): Secondary axes cannot set the aspect ratio, so calling this just sets a warning. """ - cbook._warn_external("Secondary axes can't set the aspect ratio") + _api.warn_external("Secondary axes can't set the aspect ratio") def set_color(self, color): """ diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py index 2724cd7b1a02..d4f4da74915d 100644 --- a/lib/matplotlib/axis.py +++ b/lib/matplotlib/axis.py @@ -1390,9 +1390,9 @@ def grid(self, b=None, which='major', **kwargs): raise ValueError( "'b' and 'visible' specify inconsistent grid visibilities") if kwargs and not b: # something false-like but not None - cbook._warn_external('First parameter to grid() is false, ' - 'but line properties are supplied. The ' - 'grid will be enabled.') + _api.warn_external('First parameter to grid() is false, ' + 'but line properties are supplied. The ' + 'grid will be enabled.') b = True which = which.lower() _api.check_in_list(['major', 'minor', 'both'], which=which) @@ -1604,8 +1604,8 @@ def _set_formatter(self, formatter, level): if (isinstance(formatter, mticker.FixedFormatter) and len(formatter.seq) > 0 and not isinstance(level.locator, mticker.FixedLocator)): - cbook._warn_external('FixedFormatter should only be used together ' - 'with FixedLocator') + _api.warn_external('FixedFormatter should only be used together ' + 'with FixedLocator') if level == self.major: self.isDefault_majfmt = False diff --git a/lib/matplotlib/backend_bases.py b/lib/matplotlib/backend_bases.py index 6e5896765fc5..c0afddbe25d2 100644 --- a/lib/matplotlib/backend_bases.py +++ b/lib/matplotlib/backend_bases.py @@ -3546,7 +3546,7 @@ def show(cls, *, block=None): try: manager.show() # Emits a warning for non-interactive backend. except NonGuiException as exc: - cbook._warn_external(str(exc)) + _api.warn_external(str(exc)) if cls.mainloop is None: return if block is None: diff --git a/lib/matplotlib/backend_managers.py b/lib/matplotlib/backend_managers.py index 951978a3a06a..ada29050b711 100644 --- a/lib/matplotlib/backend_managers.py +++ b/lib/matplotlib/backend_managers.py @@ -209,8 +209,8 @@ def update_keymap(self, name, key, *args): key = [key] for k in key: if k in self._keys: - cbook._warn_external('Key %s changed from %s to %s' % - (k, self._keys[k], name)) + _api.warn_external( + f'Key {k} changed from {self._keys[k]} to {name}') self._keys[k] = name def remove_tool(self, name): @@ -267,8 +267,8 @@ def add_tool(self, name, tool, *args, **kwargs): raise ValueError('Impossible to find class for %s' % str(tool)) if name in self._tools: - cbook._warn_external('A "Tool class" with the same name already ' - 'exists, not added') + _api.warn_external('A "Tool class" with the same name already ' + 'exists, not added') return self._tools[name] tool_obj = tool_cls(self, name, *args, **kwargs) @@ -437,7 +437,6 @@ def get_tool(self, name, warn=True): return name if name not in self._tools: if warn: - cbook._warn_external("ToolManager does not control tool " - "%s" % name) + _api.warn_external(f"ToolManager does not control tool {name}") return None return self._tools[name] diff --git a/lib/matplotlib/backend_tools.py b/lib/matplotlib/backend_tools.py index 7c8a9fbfbfe6..9ce38b98701e 100644 --- a/lib/matplotlib/backend_tools.py +++ b/lib/matplotlib/backend_tools.py @@ -80,7 +80,7 @@ class ToolBase: """ def __init__(self, toolmanager, name): - cbook._warn_external( + _api.warn_external( 'The new Tool classes introduced in v1.5 are experimental; their ' 'API (including names) will likely change in future versions.') self._name = name diff --git a/lib/matplotlib/backends/backend_pdf.py b/lib/matplotlib/backends/backend_pdf.py index 903d78c7c99c..636f87c3d97b 100644 --- a/lib/matplotlib/backends/backend_pdf.py +++ b/lib/matplotlib/backends/backend_pdf.py @@ -210,12 +210,12 @@ def check_trapped(x): } for k in info: if k not in keywords: - cbook._warn_external(f'Unknown infodict keyword: {k!r}. ' - f'Must be one of {set(keywords)!r}.') + _api.warn_external(f'Unknown infodict keyword: {k!r}. ' + f'Must be one of {set(keywords)!r}.') elif not keywords[k](info[k]): - cbook._warn_external(f'Bad value for infodict keyword {k}. ' - f'Got {info[k]!r} which is not ' - f'{keywords[k].text_for_warning}.') + _api.warn_external(f'Bad value for infodict keyword {k}. ' + f'Got {info[k]!r} which is not ' + f'{keywords[k].text_for_warning}.') if 'Trapped' in info: info['Trapped'] = Name(info['Trapped']) diff --git a/lib/matplotlib/backends/backend_pgf.py b/lib/matplotlib/backends/backend_pgf.py index 54f19b7d9c32..2c1eb9de859f 100644 --- a/lib/matplotlib/backends/backend_pgf.py +++ b/lib/matplotlib/backends/backend_pgf.py @@ -628,7 +628,7 @@ def draw_image(self, gc, x, y, im, transform=None): return if not os.path.exists(getattr(self.fh, "name", "")): - cbook._warn_external( + _api.warn_external( "streamed pgf-code does not support raster graphics, consider " "using the pgf-to-pdf option.") diff --git a/lib/matplotlib/backends/qt_editor/_formlayout.py b/lib/matplotlib/backends/qt_editor/_formlayout.py index c12c93c007cc..e2b371f1652d 100644 --- a/lib/matplotlib/backends/qt_editor/_formlayout.py +++ b/lib/matplotlib/backends/qt_editor/_formlayout.py @@ -46,7 +46,7 @@ import logging from numbers import Integral, Real -from matplotlib import cbook, colors as mcolors +from matplotlib import _api, colors as mcolors from matplotlib.backends.qt_compat import QtGui, QtWidgets, QtCore _log = logging.getLogger(__name__) @@ -95,7 +95,7 @@ def to_qcolor(color): try: rgba = mcolors.to_rgba(color) except ValueError: - cbook._warn_external('Ignoring invalid color %r' % color) + _api.warn_external(f'Ignoring invalid color {color!r}') return qcolor # return invalid QColor qcolor.setRgbF(*rgba) return qcolor diff --git a/lib/matplotlib/bezier.py b/lib/matplotlib/bezier.py index e0a9bcc51aa4..1f3ce0b1b24a 100644 --- a/lib/matplotlib/bezier.py +++ b/lib/matplotlib/bezier.py @@ -8,7 +8,7 @@ import numpy as np -from matplotlib import _api, cbook +from matplotlib import _api # same algorithm as 3.8's math.comb @@ -478,7 +478,7 @@ def get_parallels(bezier2, width): cmx - c2x, cmy - c2y) if parallel_test == -1: - cbook._warn_external( + _api.warn_external( "Lines do not intersect. A straight line is used instead.") cos_t1, sin_t1 = get_cos_sin(c1x, c1y, c2x, c2y) cos_t2, sin_t2 = cos_t1, sin_t1 diff --git a/lib/matplotlib/cbook/__init__.py b/lib/matplotlib/cbook/__init__.py index c7ca110a0e04..346ae0cf5431 100644 --- a/lib/matplotlib/cbook/__init__.py +++ b/lib/matplotlib/cbook/__init__.py @@ -29,8 +29,7 @@ import matplotlib from matplotlib import _api, _c_internal_utils -from matplotlib._api import ( - warn_external as _warn_external, classproperty as _classproperty) +from matplotlib._api import classproperty as _classproperty from matplotlib._api.deprecation import ( deprecated, warn_deprecated, _deprecate_method_override, _deprecate_privatize_attribute, @@ -348,8 +347,8 @@ def _local_over_kwdict( if out is None: out = kwarg_val else: - _warn_external('"%s" keyword argument will be ignored' % key, - warning_cls) + _api.warn_external(f'"{key}" keyword argument will be ignored', + warning_cls) return out diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index 22e6448debb7..334c55249816 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -219,7 +219,7 @@ def _set_ticks_on_axis_warn(*args, **kw): # a top level function which gets put in at the axes' # set_xticks and set_yticks by ColorbarBase.__init__. - cbook._warn_external("Use the colorbar set_ticks() method instead.") + _api.warn_external("Use the colorbar set_ticks() method instead.") class _ColorbarAutoLocator(ticker.MaxNLocator): @@ -721,7 +721,7 @@ def set_ticklabels(self, ticklabels, update_ticks=True): if update_ticks: self.update_ticks() else: - cbook._warn_external("set_ticks() must have been called.") + _api.warn_external("set_ticks() must have been called.") self.stale = True def minorticks_on(self): diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py index c030687e3baf..ed92fe532f30 100644 --- a/lib/matplotlib/contour.py +++ b/lib/matplotlib/contour.py @@ -827,7 +827,7 @@ def __init__(self, ax, *args, if self.filled: if self.linewidths is not None: - cbook._warn_external('linewidths is ignored by contourf') + _api.warn_external('linewidths is ignored by contourf') # Lower and upper contour levels. lowers, uppers = self._get_lowers_and_uppers() # Ensure allkinds can be zipped below. @@ -878,9 +878,10 @@ def __init__(self, ax, *args, self.changed() # set the colors if kwargs: - s = ", ".join(map(repr, kwargs)) - cbook._warn_external('The following kwargs were not used by ' - 'contour: ' + s) + _api.warn_external( + 'The following kwargs were not used by contour: ' + + ", ".join(map(repr, kwargs)) + ) def get_transform(self): """ @@ -1111,7 +1112,7 @@ def _process_contour_level_args(self, args): levels_in = self.levels[inside] if len(levels_in) == 0: self.levels = [self.zmin] - cbook._warn_external( + _api.warn_external( "No contour levels were found within the data range.") if self.filled and len(self.levels) < 2: @@ -1433,8 +1434,7 @@ def _contour_args(self, args, kwargs): self.zmin = float(z.min()) if self.logscale and self.zmin <= 0: z = ma.masked_where(z <= 0, z) - cbook._warn_external('Log scale: values of z <= 0 have been ' - 'masked') + _api.warn_external('Log scale: values of z <= 0 have been masked') self.zmin = float(z.min()) self._process_contour_level_args(args) return (x, y, z) diff --git a/lib/matplotlib/dates.py b/lib/matplotlib/dates.py index b809c50de79a..9ea05832466a 100644 --- a/lib/matplotlib/dates.py +++ b/lib/matplotlib/dates.py @@ -1409,7 +1409,7 @@ def get_locator(self, dmin, dmax): break else: if not (self.interval_multiples and freq == DAILY): - cbook._warn_external( + _api.warn_external( f"AutoDateLocator was unable to pick an appropriate " f"interval for this date range. It may be necessary " f"to add an interval value to the AutoDateLocator's " @@ -1448,7 +1448,7 @@ def get_locator(self, dmin, dmax): else: locator = MicrosecondLocator(interval, tz=self.tz) if date2num(dmin) > 70 * 365 and interval < 1000: - cbook._warn_external( + _api.warn_external( 'Plotting microsecond time intervals for dates far from ' f'the epoch (time origin: {get_epoch()}) is not well-' 'supported. See matplotlib.dates.set_epoch to change the ' diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py index 1fdc14297b0d..f677d83d0e33 100644 --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -131,7 +131,7 @@ def add(self, key, a): a_existing = self.get(key) if a_existing is not None: super().remove((key, a_existing)) - cbook._warn_external( + _api.warn_external( "key {!r} already existed; Axes is being replaced".format(key)) # I don't think the above should ever happen. @@ -1294,7 +1294,7 @@ def subplots_adjust(self, left=None, bottom=None, right=None, top=None, """ if self.get_constrained_layout(): self.set_constrained_layout(False) - cbook._warn_external( + _api.warn_external( "This figure was using constrained_layout, but that is " "incompatible with subplots_adjust and/or tight_layout; " "disabling constrained_layout.") @@ -1621,10 +1621,10 @@ def gca(self, **kwargs): if key == ckey and isinstance(cax, projection_class): return cax else: - cbook._warn_external('Requested projection is different ' - 'from current axis projection, ' - 'creating new axis with requested ' - 'projection.') + _api.warn_external('Requested projection is different ' + 'from current axis projection, ' + 'creating new axis with requested ' + 'projection.') # no axes found, so create one which spans the figure return self.add_subplot(1, 1, 1, **kwargs) @@ -2426,7 +2426,7 @@ def show(self, warn=True): try: self.canvas.manager.show() except NonGuiException as exc: - cbook._warn_external(str(exc)) + _api.warn_external(str(exc)) def get_axes(self): """ @@ -2930,7 +2930,7 @@ def __setstate__(self, state): restore_to_pylab = state.pop('_restore_to_pylab', False) if version != _mpl_version: - cbook._warn_external( + _api.warn_external( f"This figure was saved with matplotlib version {version} and " f"is unlikely to function correctly.") @@ -3192,12 +3192,12 @@ def execute_constrained_layout(self, renderer=None): _log.debug('Executing constrainedlayout') if self._layoutgrid is None: - cbook._warn_external("Calling figure.constrained_layout, but " - "figure not setup to do constrained layout. " - " You either called GridSpec without the " - "figure keyword, you are using plt.subplot, " - "or you need to call figure or subplots " - "with the constrained_layout=True kwarg.") + _api.warn_external("Calling figure.constrained_layout, but " + "figure not setup to do constrained layout. " + "You either called GridSpec without the " + "figure keyword, you are using plt.subplot, " + "or you need to call figure or subplots " + "with the constrained_layout=True kwarg.") return w_pad, h_pad, wspace, hspace = self.get_constrained_layout_pads() # convert to unit-relative lengths @@ -3240,9 +3240,9 @@ def tight_layout(self, *, pad=1.08, h_pad=None, w_pad=None, rect=None): from contextlib import suppress subplotspec_list = get_subplotspec_list(self.axes) if None in subplotspec_list: - cbook._warn_external("This figure includes Axes that are not " - "compatible with tight_layout, so results " - "might be incorrect.") + _api.warn_external("This figure includes Axes that are not " + "compatible with tight_layout, so results " + "might be incorrect.") renderer = get_renderer(self) ctx = (renderer._draw_disabled() diff --git a/lib/matplotlib/gridspec.py b/lib/matplotlib/gridspec.py index 049a13ec922a..704b577099f4 100644 --- a/lib/matplotlib/gridspec.py +++ b/lib/matplotlib/gridspec.py @@ -286,7 +286,7 @@ def subplots(self, *, sharex=False, sharey=False, squeeze=True, # instead treated as a bool for sharex. This check should go away # once sharex becomes kwonly. if isinstance(sharex, Integral): - cbook._warn_external( + _api.warn_external( "sharex argument to subplots() was an integer. Did you " "intend to use subplot() (without 's')?") _api.check_in_list(["all", "row", "col", "none"], @@ -490,9 +490,9 @@ def tight_layout(self, figure, renderer=None, subplotspec_list = tight_layout.get_subplotspec_list( figure.axes, grid_spec=self) if None in subplotspec_list: - cbook._warn_external("This figure includes Axes that are not " - "compatible with tight_layout, so results " - "might be incorrect.") + _api.warn_external("This figure includes Axes that are not " + "compatible with tight_layout, so results " + "might be incorrect.") if renderer is None: renderer = tight_layout.get_renderer(figure) diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index 9093d225a958..2718d1c25364 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -416,7 +416,7 @@ def _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification=1.0, # Cast to float64 if A.dtype not in (np.float32, np.float16): if A.dtype != np.float64: - cbook._warn_external( + _api.warn_external( f"Casting input data from '{A.dtype}' to " f"'float64' for imshow") scaled_dtype = np.float64 @@ -1580,8 +1580,8 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, # semantics of duplicate keys in pnginfo is unclear. if "pnginfo" in pil_kwargs: if metadata: - cbook._warn_external("'metadata' is overridden by the " - "'pnginfo' entry in 'pil_kwargs'.") + _api.warn_external("'metadata' is overridden by the " + "'pnginfo' entry in 'pil_kwargs'.") else: metadata = { "Software": (f"Matplotlib version{mpl.__version__}, " diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py index 4553a605c67e..ff557816a865 100644 --- a/lib/matplotlib/legend.py +++ b/lib/matplotlib/legend.py @@ -28,7 +28,7 @@ import numpy as np import matplotlib as mpl -from matplotlib import _api, cbook, docstring, colors +from matplotlib import _api, docstring, colors from matplotlib.artist import Artist, allow_rasterization from matplotlib.cbook import silent_list from matplotlib.font_manager import FontProperties @@ -404,9 +404,9 @@ def __init__(self, parent, handles, labels, _lab, _hand = [], [] for label, handle in zip(labels, handles): if isinstance(label, str) and label.startswith('_'): - cbook._warn_external('The handle {!r} has a label of {!r} ' - 'which cannot be automatically added to' - ' the legend.'.format(handle, label)) + _api.warn_external('The handle {!r} has a label of {!r} ' + 'which cannot be automatically added to' + ' the legend.'.format(handle, label)) else: _lab.append(label) _hand.append(handle) @@ -744,7 +744,7 @@ def _init_legend_box(self, handles, labels, markerfirst=True): for orig_handle, lab in zip(handles, labels): handler = self.get_legend_handler(legend_handler_map, orig_handle) if handler is None: - cbook._warn_external( + _api.warn_external( "Legend does not support {!r} instances.\nA proxy artist " "may be used instead.\nSee: " "https://matplotlib.org/users/legend_guide.html" @@ -1053,7 +1053,7 @@ def _find_best_position(self, width, height, renderer, consider=None): _, _, (l, b) = min(candidates) if self._loc_used_default and time.perf_counter() - start_time > 1: - cbook._warn_external( + _api.warn_external( 'Creating legend with loc="best" can be slow with large ' 'amounts of data.') @@ -1203,8 +1203,8 @@ def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs): extra_args = () if (handles is not None or labels is not None) and args: - cbook._warn_external("You have mixed positional and keyword " - "arguments, some input may be discarded.") + _api.warn_external("You have mixed positional and keyword arguments, " + "some input may be discarded.") # if got both handles and labels as kwargs, make same length if handles and labels: diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index ff2a9b023f6c..c9ab4a6ec612 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -766,9 +766,8 @@ def specgram(x, NFFT=None, Fs=None, detrend=None, window=None, if NFFT is None: NFFT = 256 # same default as in _spectral_helper() if len(x) <= NFFT: - cbook._warn_external("Only one segment is calculated since parameter " - "NFFT (=%d) >= signal length (=%d)." % - (NFFT, len(x))) + _api.warn_external("Only one segment is calculated since parameter " + f"NFFT (={NFFT}) >= signal length (={len(x)}).") spec, freqs, t = _spectral_helper(x=x, y=None, NFFT=NFFT, Fs=Fs, detrend_func=detrend, window=window, diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py index ad144c1b39ce..4d9b36bad463 100644 --- a/lib/matplotlib/patches.py +++ b/lib/matplotlib/patches.py @@ -84,7 +84,7 @@ def __init__(self, self._fill = True # needed for set_facecolor call if color is not None: if edgecolor is not None or facecolor is not None: - cbook._warn_external( + _api.warn_external( "Setting the 'color' property will override " "the edgecolor or facecolor properties.") self.set_color(color) diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index 312f8e280ba4..f54597146fd2 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -304,7 +304,7 @@ class backend_mod(matplotlib.backend_bases._Backend): def _warn_if_gui_out_of_main_thread(): if (_get_required_interactive_framework(_backend_mod) and threading.current_thread() is not threading.main_thread()): - cbook._warn_external( + _api.warn_external( "Starting a Matplotlib GUI outside of the main thread will likely " "fail.") @@ -745,8 +745,7 @@ def figure(num=None, # autoincrement if None, else integer from 1-N all_labels = get_figlabels() if fig_label not in all_labels: if fig_label == 'all': - cbook._warn_external( - "close('all') closes all existing figures.") + _api.warn_external("close('all') closes all existing figures.") num = next_num else: inum = all_labels.index(fig_label) @@ -758,7 +757,7 @@ def figure(num=None, # autoincrement if None, else integer from 1-N if manager is None: max_open_warning = rcParams['figure.max_open_warning'] if len(allnums) == max_open_warning >= 1: - cbook._warn_external( + _api.warn_external( f"More than {max_open_warning} figures have been opened. " f"Figures created through the pyplot interface " f"(`matplotlib.pyplot.figure`) are retained until explicitly " @@ -1213,9 +1212,9 @@ def subplot(*args, **kwargs): # intended to be the sharex argument is instead treated as a # subplot index for subplot() if len(args) >= 3 and isinstance(args[2], bool): - cbook._warn_external("The subplot index argument to subplot() appears " - "to be a boolean. Did you intend to use " - "subplots()?") + _api.warn_external("The subplot index argument to subplot() appears " + "to be a boolean. Did you intend to use " + "subplots()?") # Check for nrows and ncols, which are not valid subplot args: if 'nrows' in kwargs or 'ncols' in kwargs: raise TypeError("subplot() got an unexpected keyword argument 'ncols' " @@ -2411,8 +2410,8 @@ def polar(*args, **kwargs): # If an axis already exists, check if it has a polar projection if gcf().get_axes(): if not isinstance(gca(), PolarAxes): - cbook._warn_external('Trying to create polar plot on an axis ' - 'that does not have a polar projection.') + _api.warn_external('Trying to create polar plot on an axis ' + 'that does not have a polar projection.') ax = gca(polar=True) ret = ax.plot(*args, **kwargs) return ret diff --git a/lib/matplotlib/rcsetup.py b/lib/matplotlib/rcsetup.py index 60cffd0fb39c..3aa6e898c271 100644 --- a/lib/matplotlib/rcsetup.py +++ b/lib/matplotlib/rcsetup.py @@ -167,9 +167,8 @@ def _validate_date_converter(s): return s = validate_string(s) if s not in ['auto', 'concise']: - cbook._warn_external(f'date.converter string must be "auto" ' - f'or "concise", not "{s}". Check your ' - 'matplotlibrc') + _api.warn_external(f'date.converter string must be "auto" or ' + f'"concise", not "{s}". Check your matplotlibrc') return import matplotlib.dates as mdates mdates._rcParam_helper.set_converter(s) diff --git a/lib/matplotlib/sphinxext/mathmpl.py b/lib/matplotlib/sphinxext/mathmpl.py index 1d7a93ca15b4..b86d0e841c53 100644 --- a/lib/matplotlib/sphinxext/mathmpl.py +++ b/lib/matplotlib/sphinxext/mathmpl.py @@ -6,7 +6,7 @@ import sphinx import matplotlib as mpl -from matplotlib import cbook, mathtext +from matplotlib import _api, mathtext # Define LaTeX math node: @@ -52,7 +52,7 @@ def latex2png(latex, filename, fontset='cm'): depth = mathtext.math_to_image( latex, filename, dpi=100, format="png") except Exception: - cbook._warn_external(f"Could not render math expression {latex}") + _api.warn_external(f"Could not render math expression {latex}") depth = 0 return depth diff --git a/lib/matplotlib/style/core.py b/lib/matplotlib/style/core.py index 71cd0283e7ae..0c2f632e016a 100644 --- a/lib/matplotlib/style/core.py +++ b/lib/matplotlib/style/core.py @@ -19,7 +19,7 @@ import warnings import matplotlib as mpl -from matplotlib import _api, cbook, rc_params_from_file, rcParamsDefault +from matplotlib import _api, rc_params_from_file, rcParamsDefault _log = logging.getLogger(__name__) @@ -47,7 +47,7 @@ def _remove_blacklisted_style_params(d, warn=True): for key in d: # prevent triggering RcParams.__getitem__('backend') if key in STYLE_BLACKLIST: if warn: - cbook._warn_external( + _api.warn_external( "Style includes a parameter, '{0}', that is not related " "to style. Ignoring".format(key)) else: diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index bc772eba5a96..9fa70d3d87f0 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -346,7 +346,7 @@ def test_warn_external_frame_embedded_python(): with patch.object(cbook, "sys") as mock_sys: mock_sys._getframe = Mock(return_value=None) with pytest.warns(UserWarning, match=r"\Adummy\Z"): - cbook._warn_external("dummy") + _api.warn_external("dummy") def test_to_prestep(): @@ -607,7 +607,7 @@ def test_safe_first_element_pandas_series(pd): def test_warn_external(recwarn): - cbook._warn_external("oops") + _api.warn_external("oops") assert len(recwarn) == 1 assert recwarn[0].filename == __file__ diff --git a/lib/matplotlib/text.py b/lib/matplotlib/text.py index 1e3a820a2115..c086377c843e 100644 --- a/lib/matplotlib/text.py +++ b/lib/matplotlib/text.py @@ -1760,9 +1760,9 @@ def transform(renderer) -> Transform if (xytext is None and textcoords is not None and textcoords != xycoords): - cbook._warn_external("You have used the `textcoords` kwarg, but " - "not the `xytext` kwarg. This can lead to " - "surprising results.") + _api.warn_external("You have used the `textcoords` kwarg, but " + "not the `xytext` kwarg. This can lead to " + "surprising results.") # clean up textcoords and assign default if textcoords is None: @@ -1879,7 +1879,7 @@ def update_positions(self, renderer): # Ignore frac--it is useless. frac = d.pop('frac', None) if frac is not None: - cbook._warn_external( + _api.warn_external( "'frac' option in 'arrowprops' is no longer supported;" " use 'headlength' to set the head length in points.") headlength = d.pop('headlength', 12) diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py index d740721b6c78..6e8df3d19461 100644 --- a/lib/matplotlib/ticker.py +++ b/lib/matplotlib/ticker.py @@ -1714,7 +1714,7 @@ def set_params(self, **kwargs): Do nothing, and raise a warning. Any locator class not supporting the set_params() function will call this. """ - cbook._warn_external( + _api.warn_external( "'set_params()' not defined for locator of type " + str(type(self))) @@ -2557,7 +2557,7 @@ def nonsingular(self, vmin, vmax): if not np.isfinite(vmin) or not np.isfinite(vmax): vmin, vmax = 1, 10 # Initial range, no data plotted yet. elif vmax <= 0: - cbook._warn_external( + _api.warn_external( "Data has no positive values, and therefore cannot be " "log-scaled.") vmin, vmax = 1, 10 @@ -2852,7 +2852,7 @@ def nonsingular(self, vmin, vmax): elif vmax <= 0 or vmin >= 1: # vmax <= 0 occurs when all values are negative # vmin >= 1 occurs when all values are greater than one - cbook._warn_external( + _api.warn_external( "Data has no values between 0 and 1, and therefore cannot be " "logit-scaled." ) @@ -2917,8 +2917,8 @@ def __init__(self, n=None): def __call__(self): """Return the locations of the ticks.""" if self.axis.get_scale() == 'log': - cbook._warn_external('AutoMinorLocator does not work with ' - 'logarithmic scale') + _api.warn_external('AutoMinorLocator does not work with ' + 'logarithmic scale') return [] majorlocs = self.axis.get_majorticklocs() diff --git a/lib/matplotlib/tight_layout.py b/lib/matplotlib/tight_layout.py index 6afb55084772..1a1b2a20a359 100644 --- a/lib/matplotlib/tight_layout.py +++ b/lib/matplotlib/tight_layout.py @@ -11,7 +11,7 @@ import numpy as np -from matplotlib import cbook, rcParams +from matplotlib import _api, rcParams from matplotlib.font_manager import FontProperties from matplotlib.transforms import TransformedBbox, Bbox @@ -134,14 +134,14 @@ def auto_adjust_subplotpars( margin_bottom += rel_height + pad_inches / fig_height_inch if margin_left + margin_right >= 1: - cbook._warn_external('Tight layout not applied. The left and right ' - 'margins cannot be made large enough to ' - 'accommodate all axes decorations. ') + _api.warn_external('Tight layout not applied. The left and right ' + 'margins cannot be made large enough to ' + 'accommodate all axes decorations. ') return None if margin_bottom + margin_top >= 1: - cbook._warn_external('Tight layout not applied. The bottom and top ' - 'margins cannot be made large enough to ' - 'accommodate all axes decorations. ') + _api.warn_external('Tight layout not applied. The bottom and top ' + 'margins cannot be made large enough to ' + 'accommodate all axes decorations. ') return None kwargs = dict(left=margin_left, @@ -154,9 +154,9 @@ def auto_adjust_subplotpars( # axes widths: h_axes = (1 - margin_right - margin_left - hspace * (cols - 1)) / cols if h_axes < 0: - cbook._warn_external('Tight layout not applied. tight_layout ' - 'cannot make axes width small enough to ' - 'accommodate all axes decorations') + _api.warn_external('Tight layout not applied. tight_layout ' + 'cannot make axes width small enough to ' + 'accommodate all axes decorations') return None else: kwargs["wspace"] = hspace / h_axes @@ -164,9 +164,9 @@ def auto_adjust_subplotpars( vspace = vspaces[1:-1, :].max() + vpad_inches / fig_height_inch v_axes = (1 - margin_top - margin_bottom - vspace * (rows - 1)) / rows if v_axes < 0: - cbook._warn_external('Tight layout not applied. tight_layout ' - 'cannot make axes height small enough to ' - 'accommodate all axes decorations') + _api.warn_external('Tight layout not applied. tight_layout ' + 'cannot make axes height small enough to ' + 'accommodate all axes decorations') return None else: kwargs["hspace"] = vspace / v_axes @@ -289,14 +289,14 @@ def get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer, div_row, mod_row = divmod(max_nrows, rows) div_col, mod_col = divmod(max_ncols, cols) if mod_row != 0: - cbook._warn_external('tight_layout not applied: number of rows ' - 'in subplot specifications must be ' - 'multiples of one another.') + _api.warn_external('tight_layout not applied: number of rows ' + 'in subplot specifications must be ' + 'multiples of one another.') return {} if mod_col != 0: - cbook._warn_external('tight_layout not applied: number of ' - 'columns in subplot specifications must be ' - 'multiples of one another.') + _api.warn_external('tight_layout not applied: number of ' + 'columns in subplot specifications must be ' + 'multiples of one another.') return {} rowNum1, colNum1 = divmod(num1, cols) diff --git a/lib/matplotlib/transforms.py b/lib/matplotlib/transforms.py index 1a73ae3d0443..2dc1a8f3d9c7 100644 --- a/lib/matplotlib/transforms.py +++ b/lib/matplotlib/transforms.py @@ -229,10 +229,10 @@ class BboxBase(TransformNode): @staticmethod def _check(points): if isinstance(points, np.ma.MaskedArray): - cbook._warn_external("Bbox bounds are a masked array.") + _api.warn_external("Bbox bounds are a masked array.") points = np.asarray(points) if any((points[1, :] - points[0, :]) == 0): - cbook._warn_external("Singular Bbox.") + _api.warn_external("Singular Bbox.") def frozen(self): return Bbox(self.get_points().copy()) @@ -1789,7 +1789,7 @@ def transform_affine(self, points): # points to an array in the first place. If we can use # more arrays upstream, that should help here. if not isinstance(points, (np.ma.MaskedArray, np.ndarray)): - cbook._warn_external( + _api.warn_external( f'A non-numpy array of type {type(points)} was passed in ' f'for transformation, which results in poor performance.') return self._transform_affine(points) diff --git a/lib/matplotlib/tri/triinterpolate.py b/lib/matplotlib/tri/triinterpolate.py index 5e6a2ab11888..8c649d5c27fc 100644 --- a/lib/matplotlib/tri/triinterpolate.py +++ b/lib/matplotlib/tri/triinterpolate.py @@ -1201,10 +1201,10 @@ def compute_dz(self): err0 = np.linalg.norm(Kff_coo.dot(Uf0) - Ff) if err0 < err: # Maybe a good occasion to raise a warning here ? - cbook._warn_external("In TriCubicInterpolator initialization, " - "PCG sparse solver did not converge after " - "1000 iterations. `geom` approximation is " - "used instead of `min_E`") + _api.warn_external("In TriCubicInterpolator initialization, " + "PCG sparse solver did not converge after " + "1000 iterations. `geom` approximation is " + "used instead of `min_E`") Uf = Uf0 # Building dz from Uf diff --git a/lib/mpl_toolkits/axes_grid1/inset_locator.py b/lib/mpl_toolkits/axes_grid1/inset_locator.py index 19f7ccbb1778..4af827e60f47 100644 --- a/lib/mpl_toolkits/axes_grid1/inset_locator.py +++ b/lib/mpl_toolkits/axes_grid1/inset_locator.py @@ -2,7 +2,7 @@ A collection of functions and objects for creating or placing inset axes. """ -from matplotlib import cbook, docstring +from matplotlib import _api, docstring from matplotlib.offsetbox import AnchoredOffsetbox from matplotlib.patches import Patch, Rectangle from matplotlib.path import Path @@ -474,10 +474,9 @@ def inset_axes(parent_axes, width, height, loc='upper right', if bbox_transform in [parent_axes.transAxes, parent_axes.figure.transFigure]: if bbox_to_anchor is None: - cbook._warn_external("Using the axes or figure transform " - "requires a bounding box in the respective " - "coordinates. " - "Using bbox_to_anchor=(0, 0, 1, 1) now.") + _api.warn_external("Using the axes or figure transform requires a " + "bounding box in the respective coordinates. " + "Using bbox_to_anchor=(0, 0, 1, 1) now.") bbox_to_anchor = (0, 0, 1, 1) if bbox_to_anchor is None: diff --git a/lib/mpl_toolkits/axisartist/axislines.py b/lib/mpl_toolkits/axisartist/axislines.py index 05e1d1cd6ce0..842de4f9a731 100644 --- a/lib/mpl_toolkits/axisartist/axislines.py +++ b/lib/mpl_toolkits/axisartist/axislines.py @@ -384,7 +384,7 @@ def new_fixed_axis(self, loc, ): if axes is None: - cbook._warn_external( + _api.warn_external( "'new_fixed_axis' explicitly requires the axes keyword.") axes = self.axes @@ -404,7 +404,7 @@ def new_floating_axis(self, nth_coord, value, ): if axes is None: - cbook._warn_external( + _api.warn_external( "'new_floating_axis' explicitly requires the axes keyword.") axes = self.axes diff --git a/lib/mpl_toolkits/axisartist/clip_path.py b/lib/mpl_toolkits/axisartist/clip_path.py index f12c463b7771..830dc7fa2aa9 100644 --- a/lib/mpl_toolkits/axisartist/clip_path.py +++ b/lib/mpl_toolkits/axisartist/clip_path.py @@ -1,12 +1,12 @@ import numpy as np from math import degrees -from matplotlib import cbook +from matplotlib import _api import math def atan2(dy, dx): if dx == 0 and dy == 0: - cbook._warn_external("dx and dy are 0") + _api.warn_external("dx and dy are 0") return 0 else: return math.atan2(dy, dx) diff --git a/lib/mpl_toolkits/mplot3d/axes3d.py b/lib/mpl_toolkits/mplot3d/axes3d.py index 5e5d20ea0719..0ff0ca6d7f64 100644 --- a/lib/mpl_toolkits/mplot3d/axes3d.py +++ b/lib/mpl_toolkits/mplot3d/axes3d.py @@ -600,7 +600,7 @@ def margins(self, *margins, x=None, y=None, z=None, tight=True): if x is None and y is None and z is None: if tight is not True: - cbook._warn_external(f'ignoring tight={tight!r} in get mode') + _api.warn_external(f'ignoring tight={tight!r} in get mode') return self._xmargin, self._ymargin, self._zmargin if x is not None: @@ -759,7 +759,7 @@ def set_xlim3d(self, left=None, right=None, emit=True, auto=False, right = old_right if left == right: - cbook._warn_external( + _api.warn_external( f"Attempting to set identical left == right == {left} results " f"in singular transformations; automatically expanding.") reverse = left > right @@ -813,7 +813,7 @@ def set_ylim3d(self, bottom=None, top=None, emit=True, auto=False, top = old_top if bottom == top: - cbook._warn_external( + _api.warn_external( f"Attempting to set identical bottom == top == {bottom} " f"results in singular transformations; automatically " f"expanding.") @@ -868,7 +868,7 @@ def set_zlim3d(self, bottom=None, top=None, emit=True, auto=False, top = old_top if bottom == top: - cbook._warn_external( + _api.warn_external( f"Attempting to set identical bottom == top == {bottom} " f"results in singular transformations; automatically " f"expanding.") @@ -1573,7 +1573,7 @@ def plot_surface(self, X, Y, Z, *args, norm=None, vmin=None, if Z.ndim != 2: raise ValueError("Argument Z must be 2-dimensional.") if np.any(np.isnan(Z)): - cbook._warn_external( + _api.warn_external( "Z contains NaN values. This may result in rendering " "artifacts.")