8000 Use _val_or_rc in more places · matplotlib/matplotlib@2f27efa · GitHub
[go: up one dir, main page]

Skip to content

Commit 2f27efa

Browse files
committed
Use _val_or_rc in more places
1 parent 9db1b97 commit 2f27efa

20 files changed

+94
-205
lines changed

lib/matplotlib/axes/_axes.py

Lines changed: 20 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -168,11 +168,8 @@ def set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None,
168168
Other keyword arguments are text properties, see `.Text` for a list
169169
of valid text properties.
170170
"""
171-
if loc is None:
172-
loc = mpl.rcParams['axes.titlelocation']
173-
174-
if y is None:
175-
y = mpl.rcParams['axes.titley']
171+
loc = mpl._val_or_rc(loc, 'axes.titlelocation').lower()
172+
y = mpl._val_or_rc(y, 'axes.titley')
176173
if y is None:
177174
y = 1.0
178175
else:
@@ -182,18 +179,16 @@ def set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None,
182179
titles = {'left': self._left_title,
183180
'center': self.title,
184181
'right': self._right_title}
185-
title = _api.check_getitem(titles, loc=loc.lower())
182+
title = _api.check_getitem(titles, loc=loc)
186183
default = {
187184
'fontsize': mpl.rcParams['axes.titlesize'],
188185
'fontweight': mpl.rcParams['axes.titleweight'],
189186
'verticalalignment': 'baseline',
190-
'horizontalalignment': loc.lower()}
187+
'horizontalalignment': loc}
191188
titlecolor = mpl.rcParams['axes.titlecolor']
192189
if not cbook._str_lower_equal(titlecolor, 'auto'):
193190
default["color"] = titlecolor
194-
if pad is None:
195-
pad = mpl.rcParams['axes.titlepad']
196-
self._set_title_offset_trans(float(pad))
191+
self._set_title_offset_trans(float(mpl._val_or_rc(pad, 'axes.titlepad')))
197192
title.set_text(label)
198193
title.update(default)
199194
if fontdict is not None:
@@ -3160,8 +3155,7 @@ def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0,
31603155
markerfmt = "o"
31613156
if markerfmt == '':
31623157
markerfmt = ' ' # = empty line style; '' would resolve rcParams
3163-
markerstyle, markermarker, markercolor = \
3164-
_process_plot_format(markerfmt)
3158+
markerstyle, markermarker, markercolor = _process_plot_format(markerfmt)
31653159
if markermarker is None:
31663160
markermarker = 'o'
31673161
if markerstyle is None:
@@ -3176,8 +3170,7 @@ def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0,
31763170
basestyle, basemarker, basecolor = _process_plot_format(basefmt)
31773171

31783172
# New behaviour in 3.1 is to use a LineCollection for the stemlines
3179-
if linestyle is None:
3180-
linestyle = mpl.rcParams['lines.linestyle']
3173+
linestyle = mpl._val_or_rc(linestyle, 'lines.linestyle')
31813174
xlines = self.vlines if orientation == "vertical" else self.hlines
31823175
stemlines = xlines(
31833176
locs, bottom, heads,
@@ -3745,8 +3738,7 @@ def _upcast_err(err):
37453738

37463739
# Make the style dict for caps (the "hats").
37473740
eb_cap_style = {**base_style, 'linestyle': 'none'}
3748-
if capsize is None:
3749-
capsize = mpl.rcParams["errorbar.capsize"]
3741+
capsize = mpl._val_or_rc(capsize, "errorbar.capsize")
37503742
if capsize > 0:
37513743
eb_cap_style['markersize'] = 2. * capsize
37523744
if capthick is not None:
@@ -4100,27 +4092,18 @@ def boxplot(self, x, notch=None, sym=None, vert=None,
41004092
"""
41014093

41024094
# Missing arguments default to rcParams.
4103-
if whis is None:
4104-
whis = mpl.rcParams['boxplot.whiskers']
4105-
if bootstrap is None:
4106-
bootstrap = mpl.rcParams['boxplot.bootstrap']
4095+
whis = mpl._val_or_rc(whis, 'boxplot.whiskers')
4096+
bootstrap = mpl._val_or_rc(bootstrap, 'boxplot.bootstrap')
41074097

41084098
bxpstats = cbook.boxplot_stats(x, whis=whis, bootstrap=bootstrap,
41094099
labels=tick_labels, autorange=autorange)
4110-
if notch is None:
4111-
notch = mpl.rcParams['boxplot.notch']
4112-
if patch_artist is None:
4113-
patch_artist = mpl.rcParams['boxplot.patchartist']
4114-
if meanline is None:
4115-
meanline = mpl.rcParams['boxplot.meanline']
4116-
if showmeans is None:
4117-
showmeans = mpl.rcParams['boxplot.showmeans']
4118-
if showcaps is None:
4119-
showcaps = mpl.rcParams['boxplot.showcaps']
4120-
if showbox is None:
4121-
showbox = mpl.rcParams['boxplot.showbox']
4122-
if showfliers is None:
4123-
showfliers = mpl.rcParams['boxplot.showfliers']
4100+
notch = mpl._val_or_rc(notch, 'boxplot.notch')
4101+
patch_artist = mpl._val_or_rc(patch_artist, 'boxplot.patchartist')
4102+
meanline = mpl._val_or_rc(meanline, 'boxplot.meanline')
4103+
showmeans = mpl._val_or_rc(showmeans, 'boxplot.showmeans')
4104+
showcaps = mpl._val_or_rc(showcaps, 'boxplot.showcaps')
4105+
showbox = mpl._val_or_rc(showbox, 'boxplot.showbox')
4106+
showfliers = mpl._val_or_rc(showfliers, 'boxplot.showfliers')
41244107

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

49334916
# load default marker from rcParams
4934-
if marker is None:
4935-
marker = mpl.rcParams['scatter.marker']
4917+
marker = mpl._val_or_rc(marker, 'scatter.marker')
49364918

49374919
if isinstance(marker, mmarkers.MarkerStyle):
49384920
marker_obj = marker
@@ -6478,9 +6460,7 @@ def pcolormesh(self, *args, alpha=None, norm=None, cmap=None, vmin=None,
64786460
`~.Axes.pcolormesh`, which is not available with `~.Axes.pcolor`.
64796461
64806462
"""
6481-
if shading is None:
6482-
shading = mpl.rcParams['pcolor.shading']
6483-
shading = shading.lower()
6463+
shading = mpl._val_or_rc(shading, 'pcolor.shading').lower()
64846464
kwargs.setdefault('edgecolors', 'none')
64856465

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

6988-
if bins is None:
6989-
bins = mpl.rcParams['hist.bins']
6968+
bins = mpl._val_or_rc(bins, 'hist.bins')
69906969

69916970
# Validate string inputs here to avoid cluttering subsequent code.
69926971
_api.check_in_list(['bar', 'barstacked', 'step', 'stepfilled'],

lib/matplotlib/axes/_base.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -220,10 +220,8 @@ def __init__(self, output='Line2D'):
220220
self.set_prop_cycle(None)
221221

222222
def set_prop_cycle(self, cycler):
223-
if cycler is None:
224-
cycler = mpl.rcParams['axes.prop_cycle']
225223
self._idx = 0
226-
self._cycler_items = [*cycler]
224+
self._cycler_items = [*mpl._val_or_rc(cycler, 'axes.prop_cycle')]
227225

228226
def __call__(self, axes, *args, data=None, return_kwargs=False, **kwargs):
229227
axes._process_unit_info(kwargs=kwargs)
@@ -687,9 +685,7 @@ def __init__(self, fig,
687685

688686
# this call may differ for non-sep axes, e.g., polar
689687
self._init_axis()
690-
if facecolor is None:
691-
facecolor = mpl.rcParams['axes.facecolor']
692-
self._facecolor = facecolor
688+
self._facecolor = mpl._val_or_rc(facecolor, 'axes.facecolor')
693689
self._frameon = frameon
694690
self.set_axisbelow(mpl.rcParams['axes.axisbelow'])
695691

@@ -3587,8 +3583,7 @@ def set_xlabel(self, xlabel, fontdict=None, labelpad=None, *,
35873583
f"supplied")
35883584

35893585
else:
3590-
loc = (loc if loc is not None
3591-
else mpl.rcParams['xaxis.labellocation'])
3586+
loc = mpl._val_or_rc(loc, 'xaxis.labellocation')
35923587
_api.check_in_list(('left', 'center', 'right'), loc=loc)
35933588

35943589
x = {
@@ -3856,8 +3851,7 @@ def set_ylabel(self, ylabel, fontdict=None, labelpad=None, *,
38563851
f"supplied")
38573852

38583853
else:
3859-
loc = (loc if loc is not None
3860-
else mpl.rcParams['yaxis.labellocation'])
3854+
loc = mpl._val_or_rc(loc, 'yaxis.labellocation')
38613855
_api.check_in_list(('bottom', 'center', 'top'), loc=loc)
38623856

38633857
y, ha = {

lib/matplotlib/axis.py

Lines changed: 12 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -89,9 +89,9 @@ def __init__(
8989

9090
if gridOn is None:
9191
which = mpl.rcParams['axes.grid.which']
92-
if major and (which in ('both', 'major')):
92+
if major and which in ('both', 'major'):
9393
gridOn = mpl.rcParams['axes.grid']
94-
elif (not major) and (which in ('both', 'minor')):
94+
elif not major and which in ('both', 'minor'):
9595
gridOn = mpl.rcParams['axes.grid']
9696
else:
9797
gridOn = False
@@ -104,31 +104,15 @@ def __init__(
104104

105105
name = self.__name__
106106
major_minor = "major" if major else "minor"
107-
108-
if size is None:
109-
size = mpl.rcParams[f"{name}.{major_minor}.size"]
110-
self._size = size
111-
112-
if width is None:
113-
width = mpl.rcParams[f"{name}.{major_minor}.width"]
114-
self._width = width
115-
116-
if color is None:
117-
color = mpl.rcParams[f"{name}.color"]
118-
119-
if pad is None:
120-
pad = mpl.rcParams[f"{name}.{major_minor}.pad"]
121-
self._base_pad = pad
122-
123-
if labelcolor is None:
124-
labelcolor = mpl.rcParams[f"{name}.labelcolor"]
125-
107+
self._size = mpl._val_or_rc(size, f"{name}.{major_minor}.size")
108+
self._width = mpl._val_or_rc(width, f"{name}.{major_minor}.width")
109+
self._base_pad = mpl._val_or_rc(pad, f"{name}.{major_minor}.pad")
110+
color = mpl._val_or_rc(color, f"{name}.color")
111+
labelcolor = mpl._val_or_rc(labelcolor, f"{name}.labelcolor")
126112
if cbook._str_equal(labelcolor, 'inherit'):
127113
# inherit from tick color
128114
labelcolor = mpl.rcParams[f"{name}.color"]
129-
130-
if labelsize is None:
131-
labelsize = mpl.rcParams[f"{name}.labelsize"]
115+
labelsize = mpl._val_or_rc(labelsize, f"{name}.labelsize")
132116

133117
self._set_labelrotation(labelrotation)
134118

@@ -154,12 +138,12 @@ def __init__(
154138
self.tick1line = mlines.Line2D(
155139
[], [],
156140
color=color, linestyle="none", zorder=zorder, visible=tick1On,
157-
markeredgecolor=color, markersize=size, markeredgewidth=width,
141+
markeredgecolor=color, markersize=self._size, markeredgewidth=self._width,
158142
)
159143
self.tick2line = mlines.Line2D(
160144
[], [],
161145
color=color, linestyle="none", zorder=zorder, visible=tick2On,
162-
markeredgecolor=color, markersize=size, markeredgewidth=width,
146+
markeredgecolor=color, markersize=self._size, markeredgewidth=self._width,
163147
)
164148
self.gridline = mlines.Line2D(
165149
[], [],
@@ -208,10 +192,8 @@ def _apply_tickdir(self, tickdir):
208192
# the tick{1,2}line markers. From the user perspective this should always be
209193
# called through _apply_params, which further updates ticklabel positions using
210194
# the new pads.
211-
if tickdir is None:
212-
tickdir = mpl.rcParams[f'{self.__name__}.direction']
213-
else:
214-
_api.check_in_list(['in', 'out', 'inout'], tickdir=tickdir)
195+
tickdir = mpl._val_or_rc(tickdir, f'{self.__name__}.direction')
196+
_api.check_in_list(['in', 'out', 'inout'], tickdir=tickdir)
215197
self._tickdir = tickdir
216198

217199
def get_tickdir(self):

lib/matplotlib/backend_bases.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2115,8 +2115,7 @@ def print_figure(
21152115
filename = filename.rstrip('.') + '.' + format
21162116
format = format.lower()
21172117

2118-
if dpi is None:
2119-
dpi = rcParams['savefig.dpi']
2118+
dpi = mpl._val_or_rc(dpi, 'savefig.dpi')
21202119
if dpi == 'figure':
21212120
dpi = getattr(self.figure, '_original_dpi', self.figure.dpi)
21222121

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

2132-
for prop in ["facecolor", "edgecolor"]:
2133-
color = locals()[prop]
2134-
if color is None:
2135-
color = rcParams[f"savefig.{prop}"]
2131+
for prop, color in [("facecolor", facecolor), ("edgecolor", edgecolor)]:
2132+
color = mpl._val_or_rc(color, f"savefig.{prop}")
21362133
if not cbook._str_equal(color, "auto"):
21372134
stack.enter_context(self.figure._cm_set(**{prop: color}))
21382135

2139-
if bbox_inches is None:
2140-
bbox_inches = rcParams['savefig.bbox']
2136+
bbox_inches = mpl._val_or_rc(bbox_inches, 'savefig.bbox')
21412137

21422138
layout_engine = self.figure.get_layout_engine()
21432139
if layout_engine is not None or bbox_inches == "tight":

lib/matplotlib/cm.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -270,8 +270,7 @@ def get_cmap(name=None, lut=None):
270270
-------
271271
Colormap
272272
"""
273-
if name is None:
274-
name = mpl.rcParams['image.cmap']
273+
name = mpl._val_or_rc(name, 'image.cmap')
275274
if isinstance(name, colors.Colormap):
276275
return name
277276
_api.check_in_list(sorted(_colormaps), name=name)
@@ -302,7 +301,7 @@ def _ensure_cmap(cmap):
302301
"""
303302
if isinstance(cmap, colors.Colormap):
304303
return cmap
305-
cmap_name = cmap if cmap is not None else mpl.rcParams["image.cmap"]
304+
cmap_name = mpl._val_or_rc(cmap, "image.cmap")
306305
# use check_in_list to ensure type stability of the exception raised by
307306
# the internal usage of this (ValueError vs KeyError)
308307
if cmap_name not in _colormaps:

lib/matplotlib/contour.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -702,12 +702,8 @@ def __init__(self, ax, *args,
702702
self.origin = mpl.rcParams['image.origin']
703703

704704
self._orig_linestyles = linestyles # Only kept for user access.
705-
self.negative_linestyles = negative_linestyles
706-
# If negative_linestyles was not defined as a keyword argument, define
707-
# negative_linestyles with rcParams
708-
if self.negative_linestyles is None:
709-
self.negative_linestyles = \
710-
mpl.rcParams['contour.negative_linestyle']
705+
self.negative_linestyles = mpl._val_or_rc(negative_linestyles,
706+
'contour.negative_linestyle')
711707

712708
kwargs = self._process_args(*args, **kwargs)
713709
self._process_levels()
@@ -1314,8 +1310,7 @@ def _process_args(self, *args, corner_mask=None, algorithm=None, **kwargs):
13141310
else:
13151311
import contourpy
13161312

1317-
if algorithm is None:
1318-
algorithm = mpl.rcParams['contour.algorithm']
1313+
algorithm = mpl._val_or_rc(algorithm, 'contour.algorithm')
13191314
mpl.rcParams.validate["contour.algorithm"](algorithm)
13201315
self._algorithm = algorithm
13211316

lib/matplotlib/figure.py

Lines changed: 10 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2270,10 +2270,8 @@ def __init__(self, parent, subplotspec, *,
22702270
super().__init__(**kwargs)
22712271
if facecolor is None:
22722272
facecolor = "none"
2273-
if edgecolor is None:
2274-
edgecolor = mpl.rcParams['figure.edgecolor']
2275-
if frameon is None:
2276-
frameon = mpl.rcParams['figure.frameon']
2273+
edgecolor = mpl._val_or_rc(edgecolor, 'figure.edgecolor')
2274+
frameon = mpl._val_or_rc(frameon, 'figure.frameon')
22772275

22782276
self._subplotspec = subplotspec
22792277
self._parent = parent
@@ -2609,16 +2607,11 @@ def __init__(self,
26092607
self._button_pick_id = connect('button_press_event', self.pick)
26102608
self._scroll_pick_id = connect('scroll_event', self.pick)
26112609

2612-
if figsize is None:
2613-
figsize = mpl.rcParams['figure.figsize']
2614-
if dpi is None:
2615-
dpi = mpl.rcParams['figure.dpi']
2616-
if facecolor is None:
2617-
facecolor = mpl.rcParams['figure.facecolor']
2618-
if edgecolor is None:
2619-
edgecolor = mpl.rcParams['figure.edgecolor']
2620-
if frameon is None:
2621-
frameon = mpl.rcParams['figure.frameon']
2610+
figsize = mpl._val_or_rc(figsize, 'figure.figsize')
2611+
dpi = mpl._val_or_rc(dpi, 'figure.dpi')
2612+
facecolor = mpl._val_or_rc(facecolor, 'figure.facecolor')
2613+
edgecolor = mpl._val_or_rc(edgecolor, 'figure.edgecolor')
2614+
frameon = mpl._val_or_rc(frameon, 'figure.frameon')
26222615

26232616
if not np.isfinite(figsize).all() or (np.array(figsize) < 0).any():
26242617
raise ValueError('figure size must be positive finite not '
@@ -2891,8 +2884,7 @@ def set_tight_layout(self, tight):
28912884
If a dict, pass it as kwargs to `.Figure.tight_layout`, overriding the
28922885
default paddings.
28932886
"""
2894-
if tight is None:
2895-
tight = mpl.rcParams['figure.autolayout']
2887+
tight = mpl._val_or_rc(tight, 'figure.autolayout')
28962888
_tight = 'tight' if bool(tight) else 'none'
28972889
_tight_parameters = tight if isinstance(tight, dict) else {}
28982890
self.set_layout_engine(_tight, **_tight_parameters)
@@ -2923,8 +2915,7 @@ def set_constrained_layout(self, constrained):
29232915
----------
29242916
constrained : bool or dict or None
29252917
"""
2926-
if constrained is None:
2927-
constrained = mpl.rcParams['figure.constrained_layout.use']
2918+
constrained = mpl._val_or_rc(constrained, 'figure.constrained_layout.use')
29282919
_constrained = 'constrained' if bool(constrained) else 'none'
29292920
_parameters = constrained if isinstance(constrained, dict) else {}
29302921
self.set_layout_engine(_constrained, **_parameters)
@@ -3451,8 +3442,7 @@ def savefig(self, fname, *, transparent=None, **kwargs):
34513442
"""
34523443

34533444
kwargs.setdefault('dpi', mpl.rcParams['savefig.dpi'])
3454-
if transparent is None:
3455-
transparent = mpl.rcParams['savefig.transparent']
3445+
transparent = mpl._val_or_rc(transparent, 'savefig.transparent')
34563446

34573447
with ExitStack() as stack:
34583448
if transparent:

0 commit comments

Comments
 (0)
0