From 438d30b227b1fef7e8733578f851e76a8e360f24 Mon Sep 17 00:00:00 2001 From: Oscar Gustafsson Date: Fri, 19 Aug 2022 16:13:42 +0200 Subject: [PATCH] Get rcParams from mpl --- .../custom_legends.py | 5 +- lib/matplotlib/_layoutgrid.py | 8 +- lib/matplotlib/_tight_layout.py | 7 +- lib/matplotlib/axes/_axes.py | 92 ++++++++++--------- lib/matplotlib/colors.py | 3 +- lib/matplotlib/font_manager.py | 26 +++--- lib/matplotlib/gridspec.py | 9 +- lib/matplotlib/lines.py | 33 +++---- lib/matplotlib/markers.py | 7 +- lib/matplotlib/mathtext.py | 5 +- lib/matplotlib/offsetbox.py | 9 +- lib/matplotlib/projections/geo.py | 5 +- lib/matplotlib/projections/polar.py | 5 +- lib/matplotlib/spines.py | 12 +-- lib/matplotlib/streamplot.py | 6 +- .../tests/test_backends_interactive.py | 11 ++- .../tests/test_constrainedlayout.py | 5 +- lib/matplotlib/tests/test_figure.py | 4 +- lib/matplotlib/texmanager.py | 14 +-- lib/mpl_toolkits/axisartist/axis_artist.py | 29 +++--- lib/mpl_toolkits/axisartist/axislines.py | 16 ++-- 21 files changed, 163 insertions(+), 148 deletions(-) diff --git a/examples/text_labels_and_annotations/custom_legends.py b/examples/text_labels_and_annotations/custom_legends.py index e9f840fe768f..7f4ca07398f4 100644 --- a/examples/text_labels_and_annotations/custom_legends.py +++ b/examples/text_labels_and_annotations/custom_legends.py @@ -19,7 +19,8 @@ and call ``ax.legend()``, you will get the following: """ # sphinx_gallery_thumbnail_number = 2 -from matplotlib import rcParams, cycler +import matplotlib as mpl +from matplotlib import cycler import matplotlib.pyplot as plt import numpy as np @@ -29,7 +30,7 @@ N = 10 data = (np.geomspace(1, 10, 100) + np.random.randn(N, 100)).T cmap = plt.cm.coolwarm -rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N))) +mpl.rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N))) fig, ax = plt.subplots() lines = ax.plot(data) diff --git a/lib/matplotlib/_layoutgrid.py b/lib/matplotlib/_layoutgrid.py index 18e0274e4710..12eec6f2b2d6 100644 --- a/lib/matplotlib/_layoutgrid.py +++ b/lib/matplotlib/_layoutgrid.py @@ -20,6 +20,9 @@ import kiwisolver as kiwi import logging import numpy as np + +import matplotlib as mpl +import matplotlib.patches as mpatches from matplotlib.transforms import Bbox _log = logging.getLogger(__name__) @@ -509,13 +512,10 @@ def seq_id(): def plot_children(fig, lg=None, level=0): """Simple plotting to show where boxes are.""" - import matplotlib.pyplot as plt - import matplotlib.patches as mpatches - if lg is None: _layoutgrids = fig.get_layout_engine().execute(fig) lg = _layoutgrids[fig] - colors = plt.rcParams["axes.prop_cycle"].by_key()["color"] + colors = mpl.rcParams["axes.prop_cycle"].by_key()["color"] col = colors[level] for i in range(lg.nrows): for j in range(lg.ncols): diff --git a/lib/matplotlib/_tight_layout.py b/lib/matplotlib/_tight_layout.py index 9614bc29c222..192c2dcfdcb9 100644 --- a/lib/matplotlib/_tight_layout.py +++ b/lib/matplotlib/_tight_layout.py @@ -11,7 +11,8 @@ import numpy as np -from matplotlib import _api, artist as martist, rcParams +import matplotlib as mpl +from matplotlib import _api, artist as martist from matplotlib.font_manager import FontProperties from matplotlib.transforms import Bbox @@ -46,8 +47,8 @@ def _auto_adjust_subplotpars( """ rows, cols = shape - font_size_inch = ( - FontProperties(size=rcParams["font.size"]).get_size_in_points() / 72) + font_size_inch = (FontProperties( + size=mpl.rcParams["font.size"]).get_size_in_points() / 72) pad_inch = pad * font_size_inch vpad_inch = h_pad * font_size_inch if h_pad is not None else pad_inch hpad_inch = w_pad * font_size_inch if w_pad is not None else pad_inch diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index 3159a55b7e83..74b9721ee27a 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -7,6 +7,7 @@ import numpy as np from numpy import ma +import matplotlib as mpl import matplotlib.category # Register category unit converter as side-effect. import matplotlib.cbook as cbook import matplotlib.collections as mcoll @@ -29,7 +30,7 @@ import matplotlib.transforms as mtransforms import matplotlib.tri as mtri import matplotlib.units as munits -from matplotlib import _api, _docstring, _preprocess_data, rcParams +from matplotlib import _api, _docstring, _preprocess_data from matplotlib.axes._base import ( _AxesBase, _TransformedBoundsLocator, _process_plot_format) from matplotlib.axes._secondary_axes import SecondaryAxis @@ -136,10 +137,10 @@ def set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None, of valid text properties. """ if loc is None: - loc = rcParams['axes.titlelocation'] + loc = mpl.rcParams['axes.titlelocation'] if y is None: - y = rcParams['axes.titley'] + y = mpl.rcParams['axes.titley'] if y is None: y = 1.0 else: @@ -151,15 +152,15 @@ def set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None, 'right': self._right_title} title = _api.check_getitem(titles, loc=loc.lower()) default = { - 'fontsize': rcParams['axes.titlesize'], - 'fontweight': rcParams['axes.titleweight'], + 'fontsize': mpl.rcParams['axes.titlesize'], + 'fontweight': mpl.rcParams['axes.titleweight'], 'verticalalignment': 'baseline', 'horizontalalignment': loc.lower()} - titlecolor = rcParams['axes.titlecolor'] + titlecolor = mpl.rcParams['axes.titlecolor'] if not cbook._str_lower_equal(titlecolor, 'auto'): default["color"] = titlecolor if pad is None: - pad = rcParams['axes.titlepad'] + pad = mpl.rcParams['axes.titlepad'] self._set_title_offset_trans(float(pad)) title.set_text(label) title.update(default) @@ -2330,7 +2331,7 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center", ezorder += 0.01 error_kw.setdefault('zorder', ezorder) ecolor = kwargs.pop('ecolor', 'k') - capsize = kwargs.pop('capsize', rcParams["errorbar.capsize"]) + capsize = kwargs.pop('capsize', mpl.rcParams["errorbar.capsize"]) error_kw.setdefault('ecolor', ecolor) error_kw.setdefault('capsize', capsize) @@ -2967,13 +2968,14 @@ def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0, # resolve baseline format if basefmt is None: basefmt = (args[2] if len(args) > 2 else - "C2-" if rcParams["_internal.classic_mode"] else "C3-") + "C2-" if mpl.rcParams["_internal.classic_mode"] else + "C3-") basestyle, basemarker, basecolor = _process_plot_format(basefmt) # New behaviour in 3.1 is to use a LineCollection for the stemlines if use_line_collection: if linestyle is None: - linestyle = rcParams['lines.linestyle'] + linestyle = mpl.rcParams['lines.linestyle'] xlines = self.vlines if orientation == "vertical" else self.hlines stemlines = xlines( locs, bottom, heads, @@ -3207,7 +3209,7 @@ def get_next_color(): horizontalalignment=label_alignment_h, verticalalignment=label_alignment_v, rotation=label_rotation, - size=rcParams['xtick.labelsize']) + size=mpl.rcParams['xtick.labelsize']) t.set(**textprops) texts.append(t) @@ -3526,7 +3528,7 @@ def _upcast_err(err): # Make the style dict for caps (the "hats"). eb_cap_style = {**base_style, 'linestyle': 'none'} if capsize is None: - capsize = rcParams["errorbar.capsize"] + capsize = mpl.rcParams["errorbar.capsize"] if capsize > 0: eb_cap_style['markersize'] = 2. * capsize if capthick is not None: @@ -3819,28 +3821,28 @@ def boxplot(self, x, notch=None, sym=None, vert=None, whis=None, # Missing arguments default to rcParams. if whis is None: - whis = rcParams['boxplot.whiskers'] + whis = mpl.rcParams['boxplot.whiskers'] if bootstrap is None: - bootstrap = rcParams['boxplot.bootstrap'] + bootstrap = mpl.rcParams['boxplot.bootstrap'] bxpstats = cbook.boxplot_stats(x, whis=whis, bootstrap=bootstrap, labels=labels, autorange=autorange) if notch is None: - notch = rcParams['boxplot.notch'] + notch = mpl.rcParams['boxplot.notch'] if vert is None: - vert = rcParams['boxplot.vertical'] + vert = mpl.rcParams['boxplot.vertical'] if patch_artist is None: - patch_artist = rcParams['boxplot.patchartist'] + patch_artist = mpl.rcParams['boxplot.patchartist'] if meanline is None: - meanline = rcParams['boxplot.meanline'] + meanline = mpl.rcParams['boxplot.meanline'] if showmeans is None: - showmeans = rcParams['boxplot.showmeans'] + showmeans = mpl.rcParams['boxplot.showmeans'] if showcaps is None: - showcaps = rcParams['boxplot.showcaps'] + showcaps = mpl.rcParams['boxplot.showcaps'] if showbox is None: - showbox = rcParams['boxplot.showbox'] + showbox = mpl.rcParams['boxplot.showbox'] if showfliers is None: - showfliers = rcParams['boxplot.showfliers'] + showfliers = mpl.rcParams['boxplot.showfliers'] if boxprops is None: boxprops = {} @@ -4048,7 +4050,7 @@ def bxp(self, bxpstats, positions=None, widths=None, vert=True, zdelta = 0.1 def merge_kw_rc(subkey, explicit, zdelta=0, usemarker=True): - d = {k.split('.')[-1]: v for k, v in rcParams.items() + d = {k.split('.')[-1]: v for k, v in mpl.rcParams.items() if k.startswith(f'boxplot.{subkey}props')} d['zorder'] = zorder + zdelta if not usemarker: @@ -4057,11 +4059,11 @@ def merge_kw_rc(subkey, explicit, zdelta=0, usemarker=True): return d box_kw = { - 'linestyle': rcParams['boxplot.boxprops.linestyle'], - 'linewidth': rcParams['boxplot.boxprops.linewidth'], - 'edgecolor': rcParams['boxplot.boxprops.color'], - 'facecolor': ('white' if rcParams['_internal.classic_mode'] - else rcParams['patch.facecolor']), + 'linestyle': mpl.rcParams['boxplot.boxprops.linestyle'], + 'linewidth': mpl.rcParams['boxplot.boxprops.linewidth'], + 'edgecolor': mpl.rcParams['boxplot.boxprops.color'], + 'facecolor': ('white' if mpl.rcParams['_internal.classic_mode'] + else mpl.rcParams['patch.facecolor']), 'zorder': zorder, **cbook.normalize_kwargs(boxprops, mpatches.PathPatch) } if patch_artist else merge_kw_rc('box', boxprops, usemarker=False) @@ -4298,13 +4300,13 @@ def _parse_scatter_color_args(c, edgecolors, kwargs, xsize, if facecolors is None: facecolors = kwcolor - if edgecolors is None and not rcParams['_internal.classic_mode']: - edgecolors = rcParams['scatter.edgecolors'] + if edgecolors is None and not mpl.rcParams['_internal.classic_mode']: + edgecolors = mpl.rcParams['scatter.edgecolors'] c_was_none = c is None if c is None: c = (facecolors if facecolors is not None - else "b" if rcParams['_internal.classic_mode'] + else "b" if mpl.rcParams['_internal.classic_mode'] else get_next_color_func()) c_is_string_or_strings = ( isinstance(c, str) @@ -4496,8 +4498,8 @@ def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None, raise ValueError("x and y must be the same size") if s is None: - s = (20 if rcParams['_internal.classic_mode'] else - rcParams['lines.markersize'] ** 2.0) + s = (20 if mpl.rcParams['_internal.classic_mode'] else + mpl.rcParams['lines.markersize'] ** 2.0) s = np.ma.ravel(s) if (len(s) not in (1, x.size) or (not np.issubdtype(s.dtype, np.floating) and @@ -4533,7 +4535,7 @@ def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None, # load default marker from rcParams if marker is None: - marker = rcParams['scatter.marker'] + marker = mpl.rcParams['scatter.marker'] if isinstance(marker, mmarkers.MarkerStyle): marker_obj = marker @@ -4574,10 +4576,10 @@ def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None, edgecolors = 'face' if linewidths is None: - linewidths = rcParams['lines.linewidth'] + linewidths = mpl.rcParams['lines.linewidth'] elif np.iterable(linewidths): linewidths = [ - lw if lw is not None else rcParams['lines.linewidth'] + lw if lw is not None else mpl.rcParams['lines.linewidth'] for lw in linewidths] offsets = np.ma.column_stack([x, y]) @@ -4614,7 +4616,7 @@ def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None, # finite size of the symbols. In v2.x, margins # are present by default, so we disable this # scatter-specific override. - if rcParams['_internal.classic_mode']: + if mpl.rcParams['_internal.classic_mode']: if self._xmargin < 0.05 and x.size > 0: self.set_xmargin(0.05) if self._ymargin < 0.05 and x.size > 0: @@ -5214,7 +5216,7 @@ def _fill_between_x_or_y( dep_dir = {"x": "y", "y": "x"}[ind_dir] - if not rcParams["_internal.classic_mode"]: + if not mpl.rcParams["_internal.classic_mode"]: kwargs = cbook.normalize_kwargs(kwargs, mcoll.Collection) if not any(c in kwargs for c in ("color", "facecolor")): kwargs["facecolor"] = \ @@ -5544,7 +5546,7 @@ def imshow(self, X, cmap=None, norm=None, aspect=None, (unassociated) alpha representation. """ if aspect is None: - aspect = rcParams['image.aspect'] + aspect = mpl.rcParams['image.aspect'] self.set_aspect(aspect) im = mimage.AxesImage(self, cmap=cmap, norm=norm, interpolation=interpolation, origin=origin, @@ -5844,7 +5846,7 @@ def pcolor(self, *args, shading=None, alpha=None, norm=None, cmap=None, """ if shading is None: - shading = rcParams['pcolor.shading'] + shading = mpl.rcParams['pcolor.shading'] shading = shading.lower() X, Y, C, shading = self._pcolorargs('pcolor', *args, shading=shading, kwargs=kwargs) @@ -6108,7 +6110,7 @@ def pcolormesh(self, *args, alpha=None, norm=None, cmap=None, vmin=None, """ if shading is None: - shading = rcParams['pcolor.shading'] + shading = mpl.rcParams['pcolor.shading'] shading = shading.lower() kwargs.setdefault('edgecolors', 'none') @@ -6118,7 +6120,7 @@ def pcolormesh(self, *args, alpha=None, norm=None, cmap=None, vmin=None, # convert to one dimensional array C = C.ravel() - kwargs.setdefault('snap', rcParams['pcolormesh.snap']) + kwargs.setdefault('snap', mpl.rcParams['pcolormesh.snap']) collection = mcoll.QuadMesh( coords, antialiased=antialiased, shading=shading, @@ -6586,7 +6588,7 @@ def hist(self, x, bins=None, range=None, density=False, weights=None, x = [x] if bins is None: - bins = rcParams['hist.bins'] + bins = mpl.rcParams['hist.bins'] # Validate string inputs here to avoid cluttering subsequent code. _api.check_in_list(['bar', 'barstacked', 'step', 'stepfilled'], @@ -6713,7 +6715,7 @@ def hist(self, x, bins=None, range=None, density=False, weights=None, if rwidth is not None: dr = np.clip(rwidth, 0, 1) elif (len(tops) > 1 and - ((not stacked) or rcParams['_internal.classic_mode'])): + ((not stacked) or mpl.rcParams['_internal.classic_mode'])): dr = 0.8 else: dr = 1.0 @@ -8109,7 +8111,7 @@ def violin(self, vpstats, positions=None, vert=True, widths=0.5, line_ends = [[-0.25], [0.25]] * np.array(widths) + positions # Colors. - if rcParams['_internal.classic_mode']: + if mpl.rcParams['_internal.classic_mode']: fillcolor = 'y' linecolor = 'r' else: diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py index 2a537b6c9b7b..1df7b6f140a8 100644 --- a/lib/matplotlib/colors.py +++ b/lib/matplotlib/colors.py @@ -288,8 +288,7 @@ def to_rgba(c, alpha=None): """ # Special-case nth color syntax because it should not be cached. if _is_nth_color(c): - from matplotlib import rcParams - prop_cycler = rcParams['axes.prop_cycle'] + prop_cycler = mpl.rcParams['axes.prop_cycle'] colors = prop_cycler.by_key().get('color', ['k']) c = colors[int(c[1:]) % len(colors)] try: diff --git a/lib/matplotlib/font_manager.py b/lib/matplotlib/font_manager.py index 815ccc944b5d..99e1fecabbeb 100644 --- a/lib/matplotlib/font_manager.py +++ b/lib/matplotlib/font_manager.py @@ -39,7 +39,7 @@ import threading import matplotlib as mpl -from matplotlib import _api, _afm, cbook, ft2font, rcParams +from matplotlib import _api, _afm, cbook, ft2font from matplotlib._fontconfig_pattern import ( parse_fontconfig_pattern, generate_fontconfig_pattern) from matplotlib.rcsetup import _validators @@ -810,7 +810,7 @@ def set_family(self, family): :rc:`text.usetex` is `True`. Default: :rc:`font.family` """ if family is None: - family = rcParams['font.family'] + family = mpl.rcParams['font.family'] if isinstance(family, str): family = [family] self._family = family @@ -824,7 +824,7 @@ def set_style(self, style): style : {'normal', 'italic', 'oblique'}, default: :rc:`font.style` """ if style is None: - style = rcParams['font.style'] + style = mpl.rcParams['font.style'] _api.check_in_list(['normal', 'italic', 'oblique'], style=style) self._slant = style @@ -837,7 +837,7 @@ def set_variant(self, variant): variant : {'normal', 'small-caps'}, default: :rc:`font.variant` """ if variant is None: - variant = rcParams['font.variant'] + variant = mpl.rcParams['font.variant'] _api.check_in_list(['normal', 'small-caps'], variant=variant) self._variant = variant @@ -853,7 +853,7 @@ def set_weight(self, weight): If int, must be in the range 0-1000. """ if weight is None: - weight = rcParams['font.weight'] + weight = mpl.rcParams['font.weight'] if weight in weight_dict: self._weight = weight return @@ -879,7 +879,7 @@ def set_stretch(self, stretch): If int, must be in the range 0-1000. """ if stretch is None: - stretch = rcParams['font.stretch'] + stretch = mpl.rcParams['font.stretch'] if stretch in stretch_dict: self._stretch = stretch return @@ -905,7 +905,7 @@ def set_size(self, size): relative to the default font size. """ if size is None: - size = rcParams['font.size'] + size = mpl.rcParams['font.size'] try: size = float(size) except ValueError: @@ -971,7 +971,7 @@ def set_math_fontfamily(self, fontfamily): .text.Text.get_math_fontfamily """ if fontfamily is None: - fontfamily = rcParams['mathtext.fontset'] + fontfamily = mpl.rcParams['mathtext.fontset'] else: valid_fonts = _validators['mathtext.fontset'].valid.values() # _check_in_list() Validates the parameter math_fontfamily as @@ -1152,7 +1152,7 @@ def get_default_size(): """ Return the default font size. """ - return rcParams['font.size'] + return mpl.rcParams['font.size'] def set_default_weight(self, weight): """ @@ -1164,7 +1164,7 @@ def set_default_weight(self, weight): def _expand_aliases(family): if family in ('sans', 'sans serif'): family = 'sans-serif' - return rcParams['font.' + family] + return mpl.rcParams['font.' + family] # Each of the scoring functions below should return a value between # 0.0 (perfect match) and 1.0 (terrible match) @@ -1342,7 +1342,7 @@ def findfont(self, prop, fontext='ttf', directory=None, # Pass the relevant rcParams (and the font manager, as `self`) to # _findfont_cached so to prevent using a stale cache entry after an # rcParam was changed. - rc_params = tuple(tuple(rcParams[key]) for key in [ + rc_params = tuple(tuple(mpl.rcParams[key]) for key in [ "font.serif", "font.sans-serif", "font.cursive", "font.fantasy", "font.monospace"]) return self._findfont_cached( @@ -1595,13 +1595,13 @@ def get_font(font_filepaths, hinting_factor=None): paths = tuple(_cached_realpath(fname) for fname in font_filepaths) if hinting_factor is None: - hinting_factor = rcParams['text.hinting_factor'] + hinting_factor = mpl.rcParams['text.hinting_factor'] return _get_font( # must be a tuple to be cached paths, hinting_factor, - _kerning_factor=rcParams['text.kerning_factor'], + _kerning_factor=mpl.rcParams['text.kerning_factor'], # also key on the thread ID to prevent segfaults with multi-threading thread_id=threading.get_ident() ) diff --git a/lib/matplotlib/gridspec.py b/lib/matplotlib/gridspec.py index ec432fdb46e5..2dc066adefa9 100644 --- a/lib/matplotlib/gridspec.py +++ b/lib/matplotlib/gridspec.py @@ -18,7 +18,7 @@ import numpy as np import matplotlib as mpl -from matplotlib import _api, _pylab_helpers, _tight_layout, rcParams +from matplotlib import _api, _pylab_helpers, _tight_layout from matplotlib.transforms import Bbox _log = logging.getLogger(__name__) @@ -430,7 +430,8 @@ def get_subplot_params(self, figure=None): - :rc:`figure.subplot.*` """ if figure is None: - kw = {k: rcParams["figure.subplot."+k] for k in self._AllowedKeys} + kw = {k: mpl.rcParams["figure.subplot."+k] + for k in self._AllowedKeys} subplotpars = mpl.figure.SubplotParams(**kw) else: subplotpars = copy.copy(figure.subplotpars) @@ -520,10 +521,10 @@ def get_subplot_params(self, figure=None): """Return a dictionary of subplot layout parameters.""" hspace = (self._hspace if self._hspace is not None else figure.subplotpars.hspace if figure is not None - else rcParams["figure.subplot.hspace"]) + else mpl.rcParams["figure.subplot.hspace"]) wspace = (self._wspace if self._wspace is not None else figure.subplotpars.wspace if figure is not None - else rcParams["figure.subplot.wspace"]) + else mpl.rcParams["figure.subplot.wspace"]) figbox = self._subplot_spec.get_position(figure) left, bottom, right, top = figbox.extents diff --git a/lib/matplotlib/lines.py b/lib/matplotlib/lines.py index c229c0b715cc..8df89373adf1 100644 --- a/lib/matplotlib/lines.py +++ b/lib/matplotlib/lines.py @@ -9,7 +9,8 @@ import numpy as np -from . import _api, cbook, colors as mcolors, _docstring, rcParams +import matplotlib as mpl +from . import _api, cbook, colors as mcolors, _docstring from .artist import Artist, allow_rasterization from .cbook import ( _to_unmasked_float_array, ls_mapper, ls_mapper_r, STEP_LOOKUP_MAP) @@ -41,7 +42,7 @@ def _get_dash_pattern(style): # dashed styles elif style in ['dashed', 'dashdot', 'dotted']: offset = 0 - dashes = tuple(rcParams['lines.{}_pattern'.format(style)]) + dashes = tuple(mpl.rcParams['lines.{}_pattern'.format(style)]) # elif isinstance(style, tuple): offset, dashes = style @@ -60,7 +61,7 @@ def _get_dash_pattern(style): def _scale_dashes(offset, dashes, lw): - if not rcParams['lines.scale_dashes']: + if not mpl.rcParams['lines.scale_dashes']: return offset, dashes scaled_offset = offset * lw scaled_dashes = ([x * lw if x is not None else None for x in dashes] @@ -313,27 +314,27 @@ def __init__(self, xdata, ydata, raise RuntimeError('ydata must be a sequence') if linewidth is None: - linewidth = rcParams['lines.linewidth'] + linewidth = mpl.rcParams['lines.linewidth'] if linestyle is None: - linestyle = rcParams['lines.linestyle'] + linestyle = mpl.rcParams['lines.linestyle'] if marker is None: - marker = rcParams['lines.marker'] + marker = mpl.rcParams['lines.marker'] if color is None: - color = rcParams['lines.color'] + color = mpl.rcParams['lines.color'] if markersize is None: - markersize = rcParams['lines.markersize'] + markersize = mpl.rcParams['lines.markersize'] if antialiased is None: - antialiased = rcParams['lines.antialiased'] + antialiased = mpl.rcParams['lines.antialiased'] if dash_capstyle is None: - dash_capstyle = rcParams['lines.dash_capstyle'] + dash_capstyle = mpl.rcParams['lines.dash_capstyle'] if dash_joinstyle is None: - dash_joinstyle = rcParams['lines.dash_joinstyle'] + dash_joinstyle = mpl.rcParams['lines.dash_joinstyle'] if solid_capstyle is None: - solid_capstyle = rcParams['lines.solid_capstyle'] + solid_capstyle = mpl.rcParams['lines.solid_capstyle'] if solid_joinstyle is None: - solid_joinstyle = rcParams['lines.solid_joinstyle'] + solid_joinstyle = mpl.rcParams['lines.solid_joinstyle'] if drawstyle is None: drawstyle = 'default' @@ -939,7 +940,7 @@ def get_markeredgecolor(self): """ mec = self._markeredgecolor if cbook._str_equal(mec, 'auto'): - if rcParams['_internal.classic_mode']: + if mpl.rcParams['_internal.classic_mode']: if self._marker.get_marker() in ('.', ','): return self._color if (self._marker.is_filled() @@ -1196,7 +1197,7 @@ def set_marker(self, marker): def _set_markercolor(self, name, has_rcdefault, val): if val is None: - val = rcParams[f"lines.{name}"] if has_rcdefault else "auto" + val = mpl.rcParams[f"lines.{name}"] if has_rcdefault else "auto" attr = f"_{name}" current = getattr(self, attr) if current is None: @@ -1248,7 +1249,7 @@ def set_markeredgewidth(self, ew): Marker edge width, in points. """ if ew is None: - ew = rcParams['lines.markeredgewidth'] + ew = mpl.rcParams['lines.markeredgewidth'] if self._markeredgewidth != ew: self.stale = True self._markeredgewidth = ew diff --git a/lib/matplotlib/markers.py b/lib/matplotlib/markers.py index de9b5a81f6a0..ace32192b322 100644 --- a/lib/matplotlib/markers.py +++ b/lib/matplotlib/markers.py @@ -139,7 +139,8 @@ import numpy as np -from . import _api, cbook, rcParams +import matplotlib as mpl +from . import _api, cbook from .path import Path from .transforms import IdentityTransform, Affine2D from ._enums import JoinStyle, CapStyle @@ -309,7 +310,7 @@ def _set_fillstyle(self, fillstyle): markerfacecolor. """ if fillstyle is None: - fillstyle = rcParams['markers.fillstyle'] + fillstyle = mpl.rcParams['markers.fillstyle'] _api.check_in_list(self.fillstyles, fillstyle=fillstyle) self._fillstyle = fillstyle self._recache() @@ -524,7 +525,7 @@ def _set_mathtext_path(self): # again, the properties could be initialised just once outside # this function text = TextPath(xy=(0, 0), s=self.get_marker(), - usetex=rcParams['text.usetex']) + usetex=mpl.rcParams['text.usetex']) if len(text.vertices) == 0: return diff --git a/lib/matplotlib/mathtext.py b/lib/matplotlib/mathtext.py index b613c3a28111..3871d9ca7bc5 100644 --- a/lib/matplotlib/mathtext.py +++ b/lib/matplotlib/mathtext.py @@ -21,7 +21,8 @@ import numpy as np -from matplotlib import _api, rcParams, _mathtext +import matplotlib as mpl +from matplotlib import _api, _mathtext from matplotlib.ft2font import FT2Image, LOAD_NO_HINTING from matplotlib.font_manager import FontProperties @@ -120,7 +121,7 @@ def render_glyph(self, ox, oy, info): else: info.font.draw_glyph_to_bitmap( self.image, ox, oy - info.metrics.iceberg, info.glyph, - antialiased=rcParams['text.antialiased']) + antialiased=mpl.rcParams['text.antialiased']) def render_rect_filled(self, x1, y1, x2, y2): if self.mode == 'bbox': diff --git a/lib/matplotlib/offsetbox.py b/lib/matplotlib/offsetbox.py index 91ddc681e450..b583e320c7c7 100644 --- a/lib/matplotlib/offsetbox.py +++ b/lib/matplotlib/offsetbox.py @@ -24,7 +24,8 @@ import numpy as np -from matplotlib import _api, _docstring, rcParams +import matplotlib as mpl +from matplotlib import _api, _docstring import matplotlib.artist as martist import matplotlib.path as mpath import matplotlib.text as mtext @@ -982,11 +983,11 @@ def __init__(self, loc, self.pad = pad if prop is None: - self.prop = FontProperties(size=rcParams["legend.fontsize"]) + self.prop = FontProperties(size=mpl.rcParams["legend.fontsize"]) else: self.prop = FontProperties._from_any(prop) if isinstance(prop, dict) and "size" not in prop: - self.prop.set_size(rcParams["legend.fontsize"]) + self.prop.set_size(mpl.rcParams["legend.fontsize"]) self.patch = FancyBboxPatch( xy=(0.0, 0.0), width=1., height=1., @@ -1402,7 +1403,7 @@ def set_fontsize(self, s=None): If *s* is not given, reset to :rc:`legend.fontsize`. """ if s is None: - s = rcParams["legend.fontsize"] + s = mpl.rcParams["legend.fontsize"] self.prop = FontProperties(size=s) self.stale = True diff --git a/lib/matplotlib/projections/geo.py b/lib/matplotlib/projections/geo.py index c9e378a98aa5..c9eaaea703e7 100644 --- a/lib/matplotlib/projections/geo.py +++ b/lib/matplotlib/projections/geo.py @@ -1,6 +1,7 @@ import numpy as np -from matplotlib import _api, rcParams +import matplotlib as mpl +from matplotlib import _api from matplotlib.axes import Axes import matplotlib.axis as maxis from matplotlib.patches import Circle @@ -51,7 +52,7 @@ def clear(self): # Why do we need to turn on yaxis tick labels, but # xaxis tick labels are already on? - self.grid(rcParams['axes.grid']) + self.grid(mpl.rcParams['axes.grid']) Axes.set_xlim(self, -np.pi, np.pi) Axes.set_ylim(self, -np.pi / 2.0, np.pi / 2.0) diff --git a/lib/matplotlib/projections/polar.py b/lib/matplotlib/projections/polar.py index b6fd61aaaba7..3c80ae3ca141 100644 --- a/lib/matplotlib/projections/polar.py +++ b/lib/matplotlib/projections/polar.py @@ -3,7 +3,8 @@ import numpy as np -from matplotlib import _api, cbook, rcParams +import matplotlib as mpl +from matplotlib import _api, cbook from matplotlib.axes import Axes import matplotlib.axis as maxis import matplotlib.markers as mmarkers @@ -773,7 +774,7 @@ def clear(self): end.set_visible(False) self.set_xlim(0.0, 2 * np.pi) - self.grid(rcParams['polaraxes.grid']) + self.grid(mpl.rcParams['polaraxes.grid']) inner = self.spines.get('inner', None) if inner: inner.set_visible(False) diff --git a/lib/matplotlib/spines.py b/lib/matplotlib/spines.py index 1f373fb177ba..3395c220a74e 100644 --- a/lib/matplotlib/spines.py +++ b/lib/matplotlib/spines.py @@ -3,8 +3,8 @@ import numpy as np -import matplotlib -from matplotlib import _api, _docstring, rcParams +import matplotlib as mpl +from matplotlib import _api, _docstring from matplotlib.artist import allow_rasterization import matplotlib.transforms as mtransforms import matplotlib.patches as mpatches @@ -56,8 +56,8 @@ def __init__(self, axes, spine_type, path, **kwargs): self.set_figure(self.axes.figure) self.spine_type = spine_type self.set_facecolor('none') - self.set_edgecolor(rcParams['axes.edgecolor']) - self.set_linewidth(rcParams['axes.linewidth']) + self.set_edgecolor(mpl.rcParams['axes.edgecolor']) + self.set_linewidth(mpl.rcParams['axes.linewidth']) self.set_capstyle('projecting') self.axis = None @@ -70,7 +70,7 @@ def __init__(self, axes, spine_type, path, **kwargs): # non-rectangular axes is currently implemented, and this lets # them pass through the spines machinery without errors.) self._position = None - _api.check_isinstance(matplotlib.path.Path, path=path) + _api.check_isinstance(mpath.Path, path=path) self._path = path # To support drawing both linear and circular spines, this @@ -432,7 +432,7 @@ def linear_spine(cls, axes, spine_type, **kwargs): else: raise ValueError('unable to make path for spine "%s"' % spine_type) result = cls(axes, spine_type, path, **kwargs) - result.set_visible(rcParams['axes.spines.{0}'.format(spine_type)]) + result.set_visible(mpl.rcParams['axes.spines.{0}'.format(spine_type)]) return result diff --git a/lib/matplotlib/streamplot.py b/lib/matplotlib/streamplot.py index 31ad96044a1e..f03a681e5527 100644 --- a/lib/matplotlib/streamplot.py +++ b/lib/matplotlib/streamplot.py @@ -5,7 +5,7 @@ import numpy as np -import matplotlib +import matplotlib as mpl from matplotlib import _api, cm, patches import matplotlib.colors as mcolors import matplotlib.collections as mcollections @@ -103,7 +103,7 @@ def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None, color = axes._get_lines.get_next_color() if linewidth is None: - linewidth = matplotlib.rcParams['lines.linewidth'] + linewidth = mpl.rcParams['lines.linewidth'] line_kw = {} arrow_kw = dict(arrowstyle=arrowstyle, mutation_scale=10 * arrowsize) @@ -231,7 +231,7 @@ def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None, lc.set_norm(norm) axes.add_collection(lc) - ac = matplotlib.collections.PatchCollection(arrows) + ac = mcollections.PatchCollection(arrows) # Adding the collection itself is broken; see #2341. for p in arrows: axes.add_patch(p) diff --git a/lib/matplotlib/tests/test_backends_interactive.py b/lib/matplotlib/tests/test_backends_interactive.py index 9dd26c02e2fa..e5e6b295e798 100644 --- a/lib/matplotlib/tests/test_backends_interactive.py +++ b/lib/matplotlib/tests/test_backends_interactive.py @@ -84,14 +84,14 @@ def _test_interactive_impl(): from unittest import TestCase import matplotlib as mpl - from matplotlib import pyplot as plt, rcParams + from matplotlib import pyplot as plt from matplotlib.backend_bases import KeyEvent - rcParams.update({ + mpl.rcParams.update({ "webagg.open_in_browser": False, "webagg.port_retries": 1, }) - rcParams.update(json.loads(sys.argv[1])) + mpl.rcParams.update(json.loads(sys.argv[1])) backend = plt.rcParams["backend"].lower() assert_equal = TestCase().assertEqual assert_raises = TestCase().assertRaises @@ -177,9 +177,10 @@ def test_interactive_backend(env, toolbar): def _test_thread_impl(): from concurrent.futures import ThreadPoolExecutor - from matplotlib import pyplot as plt, rcParams + import matplotlib as mpl + from matplotlib import pyplot as plt - rcParams.update({ + mpl.rcParams.update({ "webagg.open_in_browser": False, "webagg.port_retries": 1, }) diff --git a/lib/matplotlib/tests/test_constrainedlayout.py b/lib/matplotlib/tests/test_constrainedlayout.py index 5177a05017ea..35eb850fcd70 100644 --- a/lib/matplotlib/tests/test_constrainedlayout.py +++ b/lib/matplotlib/tests/test_constrainedlayout.py @@ -1,10 +1,11 @@ import numpy as np import pytest +import matplotlib as mpl from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms -from matplotlib import gridspec, ticker, rcParams +from matplotlib import gridspec, ticker def example_plot(ax, fontsize=12, nodec=False): @@ -291,7 +292,7 @@ def test_constrained_layout14(): @image_comparison(['constrained_layout15.png']) def test_constrained_layout15(): """Test that rcparams work.""" - rcParams['figure.constrained_layout.use'] = True + mpl.rcParams['figure.constrained_layout.use'] = True fig, axs = plt.subplots(2, 2) for ax in axs.flat: example_plot(ax, fontsize=12) diff --git a/lib/matplotlib/tests/test_figure.py b/lib/matplotlib/tests/test_figure.py index eeb9021cf041..48b4a880e089 100644 --- a/lib/matplotlib/tests/test_figure.py +++ b/lib/matplotlib/tests/test_figure.py @@ -13,7 +13,7 @@ from PIL import Image import matplotlib as mpl -from matplotlib import gridspec, rcParams +from matplotlib import gridspec from matplotlib.testing.decorators import image_comparison, check_figures_equal from matplotlib.axes import Axes from matplotlib.figure import Figure, FigureBase @@ -299,7 +299,7 @@ def test_alpha(): def test_too_many_figures(): with pytest.warns(RuntimeWarning): - for i in range(rcParams['figure.max_open_warning'] + 1): + for i in range(mpl.rcParams['figure.max_open_warning'] + 1): plt.figure() diff --git a/lib/matplotlib/texmanager.py b/lib/matplotlib/texmanager.py index 4865463a349c..edac2fec9c79 100644 --- a/lib/matplotlib/texmanager.py +++ b/lib/matplotlib/texmanager.py @@ -31,7 +31,7 @@ import numpy as np import matplotlib as mpl -from matplotlib import _api, cbook, dviread, rcParams +from matplotlib import _api, cbook, dviread _log = logging.getLogger(__name__) @@ -122,7 +122,7 @@ def get_font_config(self): @classmethod def _get_font_family_and_reduced(cls): """Return the font family name and whether the font is reduced.""" - ff = rcParams['font.family'] + ff = mpl.rcParams['font.family'] ff_val = ff[0].lower() if len(ff) == 1 else None if len(ff) == 1 and ff_val in cls._font_families: return ff_val, False @@ -142,9 +142,9 @@ def _get_font_preamble_and_command(cls): for font_family in cls._font_families: if is_reduced_font and font_family == requested_family: preambles[font_family] = cls._font_preambles[ - rcParams['font.family'][0].lower()] + mpl.rcParams['font.family'][0].lower()] else: - for font in rcParams['font.' + font_family]: + for font in mpl.rcParams['font.' + font_family]: if font.lower() in cls._font_preambles: preambles[font_family] = \ cls._font_preambles[font.lower()] @@ -195,7 +195,7 @@ def get_font_preamble(cls): @classmethod def get_custom_preamble(cls): """Return a string containing user additions to the tex preamble.""" - return rcParams['text.latex.preamble'] + return mpl.rcParams['text.latex.preamble'] @classmethod def _get_tex_source(cls, tex, fontsize): @@ -327,9 +327,9 @@ def make_png(cls, tex, fontsize, dpi): def get_grey(cls, tex, fontsize=None, dpi=None): """Return the alpha channel.""" if not fontsize: - fontsize = rcParams['font.size'] + fontsize = mpl.rcParams['font.size'] if not dpi: - dpi = rcParams['savefig.dpi'] + dpi = mpl.rcParams['savefig.dpi'] key = cls._get_tex_source(tex, fontsize), dpi alpha = cls._grey_arrayd.get(key) if alpha is None: diff --git a/lib/mpl_toolkits/axisartist/axis_artist.py b/lib/mpl_toolkits/axisartist/axis_artist.py index d431b888d091..986a1c0cca0e 100644 --- a/lib/mpl_toolkits/axisartist/axis_artist.py +++ b/lib/mpl_toolkits/axisartist/axis_artist.py @@ -75,7 +75,8 @@ import numpy as np -from matplotlib import _api, cbook, rcParams +import matplotlib as mpl +from matplotlib import _api, cbook import matplotlib.artist as martist import matplotlib.colors as mcolors import matplotlib.text as mtext @@ -781,11 +782,11 @@ def _init_line(self): if axisline_style is None: self.line = PathPatch( self._axis_artist_helper.get_line(self.axes), - color=rcParams['axes.edgecolor'], + color=mpl.rcParams['axes.edgecolor'], fill=False, - linewidth=rcParams['axes.linewidth'], - capstyle=rcParams['lines.solid_capstyle'], - joinstyle=rcParams['lines.solid_joinstyle'], + linewidth=mpl.rcParams['axes.linewidth'], + capstyle=mpl.rcParams['lines.solid_capstyle'], + joinstyle=mpl.rcParams['lines.solid_joinstyle'], transform=tran) else: self.line = axisline_style(self, transform=tran) @@ -804,14 +805,16 @@ def _init_ticks(self, **kwargs): self.major_ticks = Ticks( kwargs.get( - "major_tick_size", rcParams[f"{axis_name}tick.major.size"]), + "major_tick_size", + mpl.rcParams[f"{axis_name}tick.major.size"]), axis=self.axis, transform=trans) self.minor_ticks = Ticks( kwargs.get( - "minor_tick_size", rcParams[f"{axis_name}tick.minor.size"]), + "minor_tick_size", + mpl.rcParams[f"{axis_name}tick.minor.size"]), axis=self.axis, transform=trans) - size = rcParams[f"{axis_name}tick.labelsize"] + size = mpl.rcParams[f"{axis_name}tick.labelsize"] self.major_ticklabels = TickLabels( axis=self.axis, axis_direction=self._axis_direction, @@ -819,7 +822,7 @@ def _init_ticks(self, **kwargs): transform=trans, fontsize=size, pad=kwargs.get( - "major_tick_pad", rcParams[f"{axis_name}tick.major.pad"]), + "major_tick_pad", mpl.rcParams[f"{axis_name}tick.major.pad"]), ) self.minor_ticklabels = TickLabels( axis=self.axis, @@ -828,7 +831,7 @@ def _init_ticks(self, **kwargs): transform=trans, fontsize=size, pad=kwargs.get( - "minor_tick_pad", rcParams[f"{axis_name}tick.minor.pad"]), + "minor_tick_pad", mpl.rcParams[f"{axis_name}tick.minor.pad"]), ) def _get_tick_info(self, tick_iter): @@ -903,7 +906,7 @@ def _init_offsetText(self, direction): "", xy=(x, y), xycoords="axes fraction", xytext=(0, 0), textcoords="offset points", - color=rcParams['xtick.color'], + color=mpl.rcParams['xtick.color'], horizontalalignment=ha, verticalalignment=va, ) self.offsetText.set_transform(IdentityTransform()) @@ -927,8 +930,8 @@ def _init_label(self, **kwargs): self.label = AxisLabel( 0, 0, "__from_axes__", color="auto", - fontsize=kwargs.get("labelsize", rcParams['axes.labelsize']), - fontweight=rcParams['axes.labelweight'], + fontsize=kwargs.get("labelsize", mpl.rcParams['axes.labelsize']), + fontweight=mpl.rcParams['axes.labelweight'], axis=self.axis, transform=tr, axis_direction=self._axis_direction, diff --git a/lib/mpl_toolkits/axisartist/axislines.py b/lib/mpl_toolkits/axisartist/axislines.py index ff1d063d3fb0..fdbf41580f03 100644 --- a/lib/mpl_toolkits/axisartist/axislines.py +++ b/lib/mpl_toolkits/axisartist/axislines.py @@ -42,7 +42,7 @@ import numpy as np import matplotlib as mpl -from matplotlib import _api, rcParams +from matplotlib import _api import matplotlib.axes as maxes from matplotlib.path import Path from mpl_toolkits.axes_grid1 import mpl_axes @@ -341,10 +341,10 @@ def new_gridlines(self, ax): *axis* : "both", "x" or "y" """ - gridlines = GridlinesCollection(None, transform=ax.transData, - colors=rcParams['grid.color'], - linestyles=rcParams['grid.linestyle'], - linewidths=rcParams['grid.linewidth']) + gridlines = GridlinesCollection( + None, transform=ax.transData, colors=mpl.rcParams['grid.color'], + linestyles=mpl.rcParams['grid.linestyle'], + linewidths=mpl.rcParams['grid.linewidth']) ax._set_artist_props(gridlines) gridlines.set_grid_helper(self) @@ -488,9 +488,9 @@ def clear(self): # Init gridlines before clear() as clear() calls grid(). self.gridlines = gridlines = GridlinesCollection( None, transform=self.transData, - colors=rcParams['grid.color'], - linestyles=rcParams['grid.linestyle'], - linewidths=rcParams['grid.linewidth']) + colors=mpl.rcParams['grid.color'], + linestyles=mpl.rcParams['grid.linestyle'], + linewidths=mpl.rcParams['grid.linewidth']) self._set_artist_props(gridlines) gridlines.set_grid_helper(self.get_grid_helper())