Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def __init__(self, version):
try:
major, minor, *_ = version.split('.')
major, minor = int(major), int(minor)
except (ValueError, AttributeError):
warnings._warn_proplot(
f"Invalid version {version!r}. Defaulting to '0.0'."
)
major = minor = 0
self._version = version
super().__init__([major, minor]) # then use builtin python list sorting
_ = RcConfigurator()
#: Instance of `RcConfigurator`. This is used to change global settings.
#: See the :ref:`configuration guide ` for details.
rc = _
# Modify N of existing colormaps because ProPlot settings may have changed
# image.lut. We have to register colormaps and cycles first so that the 'cycle'
# property accepts named cycles registered by ProPlot. No performance hit here.
lut = rc['image.lut']
for cmap in pcolors._cmap_database.values():
if isinstance(cmap, mcolors.LinearSegmentedColormap):
cmap.N = lut
# Deprecated
inline_backend_fmt, rc_configurator = warnings._rename_objs(
'0.6',
inline_backend_fmt=config_inline_backend,
RcConfigurator=config_inline_backend,
)
@warnings._rename_kwargs('0.7', extend='unique')
def __init__(
self, levels, norm=None, cmap=None,
unique=None, step=None, clip=False, descending=False,
):
"""
Parameters
----------
levels : list of float
The level boundaries.
norm : `~matplotlib.colors.Normalize`, optional
The normalizer used to transform `levels` and all data passed
to `~DiscreteNorm.__call__` before discretization. The ``vmin``
and ``vmax`` of the normalizer are set to the minimum and
maximum values in `levels`.
cmap : `matplotlib.colors.Colormap`, optional
The colormap associated with this normalizer. This is used to
# each row. The label spacing/border spacing will be exactly replicated.
else:
# Message when overriding some properties
overridden = []
kwargs.pop('frameon', None) # then add back later!
for override in ('bbox_transform', 'bbox_to_anchor'):
prop = kwargs.pop(override, None)
if prop is not None:
overridden.append(override)
if ncol is not None:
warnings._warn_proplot(
'Detected list of *lists* of legend handles. '
'Ignoring user input property "ncol".'
)
if overridden:
warnings._warn_proplot(
'Ignoring user input properties '
+ ', '.join(map(repr, overridden))
+ ' for centered-row legend.'
)
# Determine space we want sub-legend to occupy as fraction of height
# NOTE: Empirical testing shows spacing fudge factor necessary to
# exactly replicate the spacing of standard aligned legends.
fontsize = kwargs.get('fontsize', None) or rc['legend.fontsize']
fontsize = rc._scale_font(fontsize)
spacing = kwargs.get('labelspacing', None) or rc['legend.labelspacing']
if pairs:
interval = 1 / len(pairs) # split up axes
interval = (((1 + spacing * 0.85) * fontsize) / 72) / height
# Iterate and draw
def _mod_colormap(cmap, *, cut, left, right, shift, reverse, samples):
"""
Modify colormap in a variety of ways.
"""
if cut is not None or left is not None or right is not None:
if isinstance(cmap, pcolors.ListedColormap):
if cut is not None:
warnings._warn_proplot(
"Invalid argument 'cut' for ListedColormap. Ignoring."
)
cmap = cmap.truncate(left=left, right=right)
else:
cmap = cmap.cut(cut, left=left, right=right)
if shift is not None:
cmap = cmap.shifted(shift)
if reverse:
cmap = cmap.reversed()
if samples is not None:
if isinstance(cmap, pcolors.ListedColormap):
cmap = cmap.copy(N=samples)
else:
cmap = cmap.to_listed(samples)
return cmap
Ensure string and convert keys with omitted dots.
"""
if not isinstance(key, str):
raise KeyError(f'Invalid key {key!r}. Must be string.')
# Translate from nodots to 'full' version
if '.' not in key:
key = rcsetup._rc_nodots.get(key, key)
# Handle deprecations
if key in rcsetup._rc_removed:
alternative, version = rcsetup._rc_removed[key]
message = f'rc setting {key!r} was removed in version {version}.'
if alternative: # provide an alternative
message = f'{message} {alternative}'
warnings._warn_proplot(warnings)
key = None
if key in rcsetup._rc_renamed:
key_new, version = rcsetup._rc_renamed[key]
warnings._warn_proplot(
f'rc setting {key!r} was renamed to {key_new} in version {version}.'
)
key = key_new
return key.lower()
if isinstance(pair, tuple):
value = pair[0]
else:
value = pair
# Translate object to string
if isinstance(value, cycler.Cycler): # special case!
value = repr(value)
elif isinstance(value, (str, numbers.Number, NoneType)):
value = str(value)
elif isinstance(value, (list, tuple, np.ndarray)) and all(
isinstance(val, (str, numbers.Number)) for val in value
):
value = ', '.join(str(val) for val in value)
else:
warnings._warn_proplot(
f'Failed to write rc setting {key} = {value!r}. Must be string, '
'number, or list or tuple thereof, or None or a cycler.'
)
continue
if value[:1] == '#': # e.g. HEX string
value = repr(value)
data.append((key, value, descrip))
# Generate string
string = ''
keylen = len(max(rcdict, key=len))
vallen = len(max((tup[1] for tup in data), key=len))
for key, value, descrip in data:
space1 = ' ' * (keylen - len(key) + 1)
space2 = ' ' * (vallen - len(value) + 2) if descrip else ''
string += f'{prefix}{key}:{space1}{value}{space2}{descrip}\n'
def _scale_factory(scale, axis, *args, **kwargs): # noqa: U100
"""
If `scale` is a `~matplotlib.scale.ScaleBase` instance, do nothing. If
it is a registered scale name, look up and instantiate that scale.
"""
if isinstance(scale, mscale.ScaleBase):
if args or kwargs:
warnings._warn_proplot(
f'Ignoring args {args} and keyword args {kwargs}.'
)
return scale # do nothing
else:
scale = scale.lower()
if scale not in scales:
raise ValueError(
f'Unknown scale {scale!r}. Options are '
+ ', '.join(map(repr, scales.keys())) + '.'
)
return scales[scale](*args, **kwargs)
def _get_filtered_dict(rcdict, warn=True):
"""
Filter out blacklisted style parameters.
"""
# NOTE: This implements bugfix: https://github.com/matplotlib/matplotlib/pull/17252
# This fix is *critical* for proplot because we always run style.use()
# when the configurator is made. Without fix backend is reset every time
# you import proplot in jupyter notebooks. So apply retroactively.
rcdict_filtered = {}
for key in rcdict:
if key in mstyle.STYLE_BLACKLIST:
if warn:
warnings._warn_proplot(
f'Dictionary includes a parameter, {key!r}, that is not related '
'to style. Ignoring.'
)
else:
rcdict_filtered[key] = rcdict[key]
return rcdict_filtered