Skip to content

Commit

Permalink
Get rcParams from mpl
Browse files Browse the repository at this point in the history
  • Loading branch information
oscargus committed Aug 19, 2022
1 parent a0f16a8 commit ea189d0
Show file tree
Hide file tree
Showing 20 changed files with 157 additions and 145 deletions.
6 changes: 3 additions & 3 deletions examples/text_labels_and_annotations/custom_legends.py
Expand Up @@ -16,10 +16,10 @@
Sometimes you don't want a legend that is explicitly tied to data that
you have plotted. For example, say you have plotted 10 lines, but don't
want a legend item to show up for each one. If you simply plot the lines
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

Expand All @@ -29,7 +29,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)
Expand Down
8 changes: 4 additions & 4 deletions lib/matplotlib/_layoutgrid.py
Expand Up @@ -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__)
Expand Down Expand Up @@ -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):
Expand Down
7 changes: 4 additions & 3 deletions lib/matplotlib/_tight_layout.py
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
92 changes: 47 additions & 45 deletions lib/matplotlib/axes/_axes.py
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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)
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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 = {}
Expand Down Expand Up @@ -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:
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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])
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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"] = \
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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')

Expand All @@ -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,
Expand Down Expand Up @@ -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'],
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/colors.py
Expand Up @@ -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:
Expand Down

0 comments on commit ea189d0

Please sign in to comment.