Skip to content

Commit

Permalink
Use _val_or_rc in more places
Browse files Browse the repository at this point in the history
  • Loading branch information
QuLogic committed Dec 20, 2024
1 parent 9db1b97 commit a916ece
Show file tree
Hide file tree
Showing 20 changed files with 94 additions and 204 deletions.
61 changes: 20 additions & 41 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,11 +168,8 @@ def set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None,
Other keyword arguments are text properties, see `.Text` for a list
of valid text properties.
"""
if loc is None:
loc = mpl.rcParams['axes.titlelocation']

if y is None:
y = mpl.rcParams['axes.titley']
loc = mpl._val_or_rc(loc, 'axes.titlelocation').lower()
y = mpl._val_or_rc(y, 'axes.titley')
if y is None:
y = 1.0
else:
Expand All @@ -182,18 +179,16 @@ def set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None,
titles = {'left': self._left_title,
'center': self.title,
'right': self._right_title}
title = _api.check_getitem(titles, loc=loc.lower())
title = _api.check_getitem(titles, loc=loc)
default = {
'fontsize': mpl.rcParams['axes.titlesize'],
'fontweight': mpl.rcParams['axes.titleweight'],
'verticalalignment': 'baseline',
'horizontalalignment': loc.lower()}
'horizontalalignment': loc}
titlecolor = mpl.rcParams['axes.titlecolor']
if not cbook._str_lower_equal(titlecolor, 'auto'):
default["color"] = titlecolor
if pad is None:
pad = mpl.rcParams['axes.titlepad']
self._set_title_offset_trans(float(pad))
self._set_title_offset_trans(float(mpl._val_or_rc(pad, 'axes.titlepad')))
title.set_text(label)
title.update(default)
if fontdict is not None:
Expand Down Expand Up @@ -3160,8 +3155,7 @@ def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0,
markerfmt = "o"
if markerfmt == '':
markerfmt = ' ' # = empty line style; '' would resolve rcParams
markerstyle, markermarker, markercolor = \
_process_plot_format(markerfmt)
markerstyle, markermarker, markercolor = _process_plot_format(markerfmt)
if markermarker is None:
markermarker = 'o'
if markerstyle is None:
Expand All @@ -3176,8 +3170,7 @@ def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0,
basestyle, basemarker, basecolor = _process_plot_format(basefmt)

# New behaviour in 3.1 is to use a LineCollection for the stemlines
if linestyle is None:
linestyle = mpl.rcParams['lines.linestyle']
linestyle = mpl._val_or_rc(linestyle, 'lines.linestyle')
xlines = self.vlines if orientation == "vertical" else self.hlines
stemlines = xlines(
locs, bottom, heads,
Expand Down Expand Up @@ -3745,8 +3738,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 = mpl.rcParams["errorbar.capsize"]
capsize = mpl._val_or_rc(capsize, "errorbar.capsize")
if capsize > 0:
eb_cap_style['markersize'] = 2. * capsize
if capthick is not None:
Expand Down Expand Up @@ -4100,27 +4092,18 @@ def boxplot(self, x, notch=None, sym=None, vert=None,
"""

# Missing arguments default to rcParams.
if whis is None:
whis = mpl.rcParams['boxplot.whiskers']
if bootstrap is None:
bootstrap = mpl.rcParams['boxplot.bootstrap']
whis = mpl._val_or_rc(whis, 'boxplot.whiskers')
bootstrap = mpl._val_or_rc(bootstrap, 'boxplot.bootstrap')

bxpstats = cbook.boxplot_stats(x, whis=whis, bootstrap=bootstrap,
labels=tick_labels, autorange=autorange)
if notch is None:
notch = mpl.rcParams['boxplot.notch']
if patch_artist is None:
patch_artist = mpl.rcParams['boxplot.patchartist']
if meanline is None:
meanline = mpl.rcParams['boxplot.meanline']
if showmeans is None:
showmeans = mpl.rcParams['boxplot.showmeans']
if showcaps is None:
showcaps = mpl.rcParams['boxplot.showcaps']
if showbox is None:
showbox = mpl.rcParams['boxplot.showbox']
if showfliers is None:
showfliers = mpl.rcParams['boxplot.showfliers']
notch = mpl._val_or_rc(notch, 'boxplot.notch')
patch_artist = mpl._val_or_rc(patch_artist, 'boxplot.patchartist')
meanline = mpl._val_or_rc(meanline, 'boxplot.meanline')
showmeans = mpl._val_or_rc(showmeans, 'boxplot.showmeans')
showcaps = mpl._val_or_rc(showcaps, 'boxplot.showcaps')
showbox = mpl._val_or_rc(showbox, 'boxplot.showbox')
showfliers = mpl._val_or_rc(showfliers, 'boxplot.showfliers')

if boxprops is None:
boxprops = {}
Expand Down Expand Up @@ -4931,8 +4914,7 @@ def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None,
scales = s # Renamed for readability below.

# load default marker from rcParams
if marker is None:
marker = mpl.rcParams['scatter.marker']
marker = mpl._val_or_rc(marker, 'scatter.marker')

if isinstance(marker, mmarkers.MarkerStyle):
marker_obj = marker
Expand Down Expand Up @@ -6478,9 +6460,7 @@ def pcolormesh(self, *args, alpha=None, norm=None, cmap=None, vmin=None,
`~.Axes.pcolormesh`, which is not available with `~.Axes.pcolor`.
"""
if shading is None:
shading = mpl.rcParams['pcolor.shading']
shading = shading.lower()
shading = mpl._val_or_rc(shading, 'pcolor.shading').lower()
kwargs.setdefault('edgecolors', 'none')

X, Y, C, shading = self._pcolorargs('pcolormesh', *args,
Expand Down Expand Up @@ -6985,8 +6965,7 @@ def hist(self, x, bins=None, range=None, density=False, weights=None,
if np.isscalar(x):
x = [x]

if bins is None:
bins = mpl.rcParams['hist.bins']
bins = mpl._val_or_rc(bins, 'hist.bins')

# Validate string inputs here to avoid cluttering subsequent code.
_api.check_in_list(['bar', 'barstacked', 'step', 'stepfilled'],
Expand Down
13 changes: 4 additions & 9 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,10 +220,8 @@ def __init__(self, output='Line2D'):
self.set_prop_cycle(None)

def set_prop_cycle(self, cycler):
if cycler is None:
cycler = mpl.rcParams['axes.prop_cycle']
self._idx = 0
self._cycler_items = [*cycler]
self._cycler_items = [*mpl._val_or_rc(cycler, 'axes.prop_cycle')]

def __call__(self, axes, *args, data=None, return_kwargs=False, **kwargs):
axes._process_unit_info(kwargs=kwargs)
Expand Down Expand Up @@ -687,8 +685,7 @@ def __init__(self, fig,

# this call may differ for non-sep axes, e.g., polar
self._init_axis()
if facecolor is None:
facecolor = mpl.rcParams['axes.facecolor']
facecolor = mpl._val_or_rc(facecolor, 'axes.facecolor')
self._facecolor = facecolor
self._frameon = frameon
self.set_axisbelow(mpl.rcParams['axes.axisbelow'])
Expand Down Expand Up @@ -3587,8 +3584,7 @@ def set_xlabel(self, xlabel, fontdict=None, labelpad=None, *,
f"supplied")

else:
loc = (loc if loc is not None
else mpl.rcParams['xaxis.labellocation'])
loc = mpl._val_or_rc(loc, 'xaxis.labellocation')
_api.check_in_list(('left', 'center', 'right'), loc=loc)

x = {
Expand Down Expand Up @@ -3856,8 +3852,7 @@ def set_ylabel(self, ylabel, fontdict=None, labelpad=None, *,
f"supplied")

else:
loc = (loc if loc is not None
else mpl.rcParams['yaxis.labellocation'])
loc = mpl._val_or_rc(loc, 'yaxis.labellocation')
_api.check_in_list(('bottom', 'center', 'top'), loc=loc)

y, ha = {
Expand Down
42 changes: 12 additions & 30 deletions lib/matplotlib/axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,9 @@ def __init__(

if gridOn is None:
which = mpl.rcParams['axes.grid.which']
if major and (which in ('both', 'major')):
if major and which in ('both', 'major'):
gridOn = mpl.rcParams['axes.grid']
elif (not major) and (which in ('both', 'minor')):
elif not major and which in ('both', 'minor'):
gridOn = mpl.rcParams['axes.grid']
else:
gridOn = False
Expand All @@ -104,31 +104,15 @@ def __init__(

name = self.__name__
major_minor = "major" if major else "minor"

if size is None:
size = mpl.rcParams[f"{name}.{major_minor}.size"]
self._size = size

if width is None:
width = mpl.rcParams[f"{name}.{major_minor}.width"]
self._width = width

if color is None:
color = mpl.rcParams[f"{name}.color"]

if pad is None:
pad = mpl.rcParams[f"{name}.{major_minor}.pad"]
self._base_pad = pad

if labelcolor is None:
labelcolor = mpl.rcParams[f"{name}.labelcolor"]

self._size = mpl._val_or_rc(size, f"{name}.{major_minor}.size")
self._width = mpl._val_or_rc(width, f"{name}.{major_minor}.width")
self._base_pad = mpl._val_or_rc(pad, f"{name}.{major_minor}.pad")
color = mpl._val_or_rc(color, f"{name}.color")
labelcolor = mpl._val_or_rc(labelcolor, f"{name}.labelcolor")
if cbook._str_equal(labelcolor, 'inherit'):
# inherit from tick color
labelcolor = mpl.rcParams[f"{name}.color"]

if labelsize is None:
labelsize = mpl.rcParams[f"{name}.labelsize"]
labelsize = mpl._val_or_rc(labelsize, f"{name}.labelsize")

self._set_labelrotation(labelrotation)

Expand All @@ -154,12 +138,12 @@ def __init__(
self.tick1line = mlines.Line2D(
[], [],
color=color, linestyle="none", zorder=zorder, visible=tick1On,
markeredgecolor=color, markersize=size, markeredgewidth=width,
markeredgecolor=color, markersize=self._size, markeredgewidth=self._width,
)
self.tick2line = mlines.Line2D(
[], [],
color=color, linestyle="none", zorder=zorder, visible=tick2On,
markeredgecolor=color, markersize=size, markeredgewidth=width,
markeredgecolor=color, markersize=self._size, markeredgewidth=self._width,
)
self.gridline = mlines.Line2D(
[], [],
Expand Down Expand Up @@ -208,10 +192,8 @@ def _apply_tickdir(self, tickdir):
# the tick{1,2}line markers. From the user perspective this should always be
# called through _apply_params, which further updates ticklabel positions using
# the new pads.
if tickdir is None:
tickdir = mpl.rcParams[f'{self.__name__}.direction']
else:
_api.check_in_list(['in', 'out', 'inout'], tickdir=tickdir)
tickdir = mpl._val_or_rc(tickdir, f'{self.__name__}.direction')
_api.check_in_list(['in', 'out', 'inout'], tickdir=tickdir)
self._tickdir = tickdir

def get_tickdir(self):
Expand Down
12 changes: 4 additions & 8 deletions lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -2115,8 +2115,7 @@ def print_figure(
filename = filename.rstrip('.') + '.' + format
format = format.lower()

if dpi is None:
dpi = rcParams['savefig.dpi']
dpi = mpl._val_or_rc(dpi, 'savefig.dpi')
if dpi == 'figure':
dpi = getattr(self.figure, '_original_dpi', self.figure.dpi)

Expand All @@ -2129,15 +2128,12 @@ def print_figure(
cbook._setattr_cm(self.figure.canvas, _is_saving=True),
ExitStack() as stack):

for prop in ["facecolor", "edgecolor"]:
color = locals()[prop]
if color is None:
color = rcParams[f"savefig.{prop}"]
for prop, color in [("facecolor", facecolor), ("edgecolor", edgecolor)]:
color = mpl._val_or_rc(color, f"savefig.{prop}")
if not cbook._str_equal(color, "auto"):
stack.enter_context(self.figure._cm_set(**{prop: color}))

if bbox_inches is None:
bbox_inches = rcParams['savefig.bbox']
bbox_inches = mpl._val_or_rc(bbox_inches, 'savefig.bbox')

layout_engine = self.figure.get_layout_engine()
if layout_engine is not None or bbox_inches == "tight":
Expand Down
5 changes: 2 additions & 3 deletions lib/matplotlib/cm.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,8 +270,7 @@ def get_cmap(name=None, lut=None):
-------
Colormap
"""
if name is None:
name = mpl.rcParams['image.cmap']
name = mpl._val_or_rc(name, 'image.cmap')
if isinstance(name, colors.Colormap):
return name
_api.check_in_list(sorted(_colormaps), name=name)
Expand Down Expand Up @@ -302,7 +301,7 @@ def _ensure_cmap(cmap):
"""
if isinstance(cmap, colors.Colormap):
return cmap
cmap_name = cmap if cmap is not None else mpl.rcParams["image.cmap"]
cmap_name = mpl._val_or_rc(cmap, "image.cmap")
# use check_in_list to ensure type stability of the exception raised by
# the internal usage of this (ValueError vs KeyError)
if cmap_name not in _colormaps:
Expand Down
11 changes: 3 additions & 8 deletions lib/matplotlib/contour.py
Original file line number Diff line number Diff line change
Expand Up @@ -702,12 +702,8 @@ def __init__(self, ax, *args,
self.origin = mpl.rcParams['image.origin']

self._orig_linestyles = linestyles # Only kept for user access.
self.negative_linestyles = negative_linestyles
# If negative_linestyles was not defined as a keyword argument, define
# negative_linestyles with rcParams
if self.negative_linestyles is None:
self.negative_linestyles = \
mpl.rcParams['contour.negative_linestyle']
self.negative_linestyles = mpl._val_or_rc(negative_linestyles,
'contour.negative_linestyle')

kwargs = self._process_args(*args, **kwargs)
self._process_levels()
Expand Down Expand Up @@ -1314,8 +1310,7 @@ def _process_args(self, *args, corner_mask=None, algorithm=None, **kwargs):
else:
import contourpy

if algorithm is None:
algorithm = mpl.rcParams['contour.algorithm']
algorithm = mpl._val_or_rc(algorithm, 'contour.algorithm')
mpl.rcParams.validate["contour.algorithm"](algorithm)
self._algorithm = algorithm

Expand Down
30 changes: 10 additions & 20 deletions lib/matplotlib/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -2270,10 +2270,8 @@ def __init__(self, parent, subplotspec, *,
super().__init__(**kwargs)
if facecolor is None:
facecolor = "none"
if edgecolor is None:
edgecolor = mpl.rcParams['figure.edgecolor']
if frameon is None:
frameon = mpl.rcParams['figure.frameon']
edgecolor = mpl._val_or_rc(edgecolor, 'figure.edgecolor')
frameon = mpl._val_or_rc(frameon, 'figure.frameon')

self._subplotspec = subplotspec
self._parent = parent
Expand Down Expand Up @@ -2609,16 +2607,11 @@ def __init__(self,
self._button_pick_id = connect('button_press_event', self.pick)
self._scroll_pick_id = connect('scroll_event', self.pick)

if figsize is None:
figsize = mpl.rcParams['figure.figsize']
if dpi is None:
dpi = mpl.rcParams['figure.dpi']
if facecolor is None:
facecolor = mpl.rcParams['figure.facecolor']
if edgecolor is None:
edgecolor = mpl.rcParams['figure.edgecolor']
if frameon is None:
frameon = mpl.rcParams['figure.frameon']
figsize = mpl._val_or_rc(figsize, 'figure.figsize')
dpi = mpl._val_or_rc(dpi, 'figure.dpi')
facecolor = mpl._val_or_rc(facecolor, 'figure.facecolor')
edgecolor = mpl._val_or_rc(edgecolor, 'figure.edgecolor')
frameon = mpl._val_or_rc(frameon, 'figure.frameon')

if not np.isfinite(figsize).all() or (np.array(figsize) < 0).any():
raise ValueError('figure size must be positive finite not '
Expand Down Expand Up @@ -2891,8 +2884,7 @@ def set_tight_layout(self, tight):
If a dict, pass it as kwargs to `.Figure.tight_layout`, overriding the
default paddings.
"""
if tight is None:
tight = mpl.rcParams['figure.autolayout']
tight = mpl._val_or_rc(tight, 'figure.autolayout')
_tight = 'tight' if bool(tight) else 'none'
_tight_parameters = tight if isinstance(tight, dict) else {}
self.set_layout_engine(_tight, **_tight_parameters)
Expand Down Expand Up @@ -2923,8 +2915,7 @@ def set_constrained_layout(self, constrained):
----------
constrained : bool or dict or None
"""
if constrained is None:
constrained = mpl.rcParams['figure.constrained_layout.use']
constrained = mpl._val_or_rc(constrained, 'figure.constrained_layout.use')
_constrained = 'constrained' if bool(constrained) else 'none'
_parameters = constrained if isinstance(constrained, dict) else {}
self.set_layout_engine(_constrained, **_parameters)
Expand Down Expand Up @@ -3451,8 +3442,7 @@ def savefig(self, fname, *, transparent=None, **kwargs):
"""

kwargs.setdefault('dpi', mpl.rcParams['savefig.dpi'])
if transparent is None:
transparent = mpl.rcParams['savefig.transparent']
transparent = mpl._val_or_rc(transparent, 'savefig.transparent')

with ExitStack() as stack:
if transparent:
Expand Down
Loading

0 comments on commit a916ece

Please sign in to comment.