'
+ '
'
+ f'{color_block(self.get_under())} under'
+ '
'
+ '
'
+ f'bad {color_block(self.get_bad())}'
+ '
'
+ '
'
+ f'over {color_block(self.get_over())}'
+ '
')
+
+ def copy(self):
+ """Return a copy of the colormap."""
+ return self.__copy__()
+
+
+class LinearSegmentedColormap(Colormap):
+ """
+ Colormap objects based on lookup tables using linear segments.
+
+ The lookup table is generated using linear interpolation for each
+ primary color, with the 0-1 domain divided into any number of
+ segments.
+ """
+
+ def __init__(self, name, segmentdata, N=256, gamma=1.0):
+ """
+ Create colormap from linear mapping segments
+
+ segmentdata argument is a dictionary with a red, green and blue
+ entries. Each entry should be a list of *x*, *y0*, *y1* tuples,
+ forming rows in a table. Entries for alpha are optional.
+
+ Example: suppose you want red to increase from 0 to 1 over
+ the bottom half, green to do the same over the middle half,
+ and blue over the top half. Then you would use::
+
+ cdict = {'red': [(0.0, 0.0, 0.0),
+ (0.5, 1.0, 1.0),
+ (1.0, 1.0, 1.0)],
+
+ 'green': [(0.0, 0.0, 0.0),
+ (0.25, 0.0, 0.0),
+ (0.75, 1.0, 1.0),
+ (1.0, 1.0, 1.0)],
+
+ 'blue': [(0.0, 0.0, 0.0),
+ (0.5, 0.0, 0.0),
+ (1.0, 1.0, 1.0)]}
+
+ Each row in the table for a given color is a sequence of
+ *x*, *y0*, *y1* tuples. In each sequence, *x* must increase
+ monotonically from 0 to 1. For any input value *z* falling
+ between *x[i]* and *x[i+1]*, the output value of a given color
+ will be linearly interpolated between *y1[i]* and *y0[i+1]*::
+
+ row i: x y0 y1
+ /
+ /
+ row i+1: x y0 y1
+
+ Hence y0 in the first row and y1 in the last row are never used.
+
+ See Also
+ --------
+ LinearSegmentedColormap.from_list
+ Static method; factory function for generating a smoothly-varying
+ LinearSegmentedColormap.
+ """
+ # True only if all colors in map are identical; needed for contouring.
+ self.monochrome = False
+ super().__init__(name, N)
+ self._segmentdata = segmentdata
+ self._gamma = gamma
+
+ def _init(self):
+ self._lut = np.ones((self.N + 3, 4), float)
+ self._lut[:-3, 0] = _create_lookup_table(
+ self.N, self._segmentdata['red'], self._gamma)
+ self._lut[:-3, 1] = _create_lookup_table(
+ self.N, self._segmentdata['green'], self._gamma)
+ self._lut[:-3, 2] = _create_lookup_table(
+ self.N, self._segmentdata['blue'], self._gamma)
+ if 'alpha' in self._segmentdata:
+ self._lut[:-3, 3] = _create_lookup_table(
+ self.N, self._segmentdata['alpha'], 1)
+ self._isinit = True
+ self._set_extremes()
+
+ def set_gamma(self, gamma):
+ """Set a new gamma value and regenerate colormap."""
+ self._gamma = gamma
+ self._init()
+
+ @staticmethod
+ def from_list(name, colors, N=256, gamma=1.0):
+ """
+ Create a `LinearSegmentedColormap` from a list of colors.
+
+ Parameters
+ ----------
+ name : str
+ The name of the colormap.
+ colors : array-like of colors or array-like of (value, color)
+ If only colors are given, they are equidistantly mapped from the
+ range :math:`[0, 1]`; i.e. 0 maps to ``colors[0]`` and 1 maps to
+ ``colors[-1]``.
+ If (value, color) pairs are given, the mapping is from *value*
+ to *color*. This can be used to divide the range unevenly.
+ N : int
+ The number of RGB quantization levels.
+ gamma : float
+ """
+ if not np.iterable(colors):
+ raise ValueError('colors must be iterable')
+
+ if (isinstance(colors[0], Sized) and len(colors[0]) == 2
+ and not isinstance(colors[0], str)):
+ # List of value, color pairs
+ vals, colors = zip(*colors)
+ else:
+ vals = np.linspace(0, 1, len(colors))
+
+ r, g, b, a = to_rgba_array(colors).T
+ cdict = {
+ "red": np.column_stack([vals, r, r]),
+ "green": np.column_stack([vals, g, g]),
+ "blue": np.column_stack([vals, b, b]),
+ "alpha": np.column_stack([vals, a, a]),
+ }
+
+ return LinearSegmentedColormap(name, cdict, N, gamma)
+
+ def resampled(self, lutsize):
+ """Return a new colormap with *lutsize* entries."""
+ new_cmap = LinearSegmentedColormap(self.name, self._segmentdata,
+ lutsize)
+ new_cmap._rgba_over = self._rgba_over
+ new_cmap._rgba_under = self._rgba_under
+ new_cmap._rgba_bad = self._rgba_bad
+ return new_cmap
+
+ # Helper ensuring picklability of the reversed cmap.
+ @staticmethod
+ def _reverser(func, x):
+ return func(1 - x)
+
+ def reversed(self, name=None):
+ """
+ Return a reversed instance of the Colormap.
+
+ Parameters
+ ----------
+ name : str, optional
+ The name for the reversed colormap. If None, the
+ name is set to ``self.name + "_r"``.
+
+ Returns
+ -------
+ LinearSegmentedColormap
+ The reversed colormap.
+ """
+ if name is None:
+ name = self.name + "_r"
+
+ # Using a partial object keeps the cmap picklable.
+ data_r = {key: (functools.partial(self._reverser, data)
+ if callable(data) else
+ [(1.0 - x, y1, y0) for x, y0, y1 in reversed(data)])
+ for key, data in self._segmentdata.items()}
+
+ new_cmap = LinearSegmentedColormap(name, data_r, self.N, self._gamma)
+ # Reverse the over/under values too
+ new_cmap._rgba_over = self._rgba_under
+ new_cmap._rgba_under = self._rgba_over
+ new_cmap._rgba_bad = self._rgba_bad
+ return new_cmap
+
+
+class ListedColormap(Colormap):
+ """
+ Colormap object generated from a list of colors.
+
+ This may be most useful when indexing directly into a colormap,
+ but it can also be used to generate special colormaps for ordinary
+ mapping.
+
+ Parameters
+ ----------
+ colors : list, array
+ List of Matplotlib color specifications, or an equivalent Nx3 or Nx4
+ floating point array (*N* RGB or RGBA values).
+ name : str, optional
+ String to identify the colormap.
+ N : int, optional
+ Number of entries in the map. The default is *None*, in which case
+ there is one colormap entry for each element in the list of colors.
+ If ::
+
+ N < len(colors)
+
+ the list will be truncated at *N*. If ::
+
+ N > len(colors)
+
+ the list will be extended by repetition.
+ """
+ def __init__(self, colors, name='from_list', N=None):
+ self.monochrome = False # Are all colors identical? (for contour.py)
+ if N is None:
+ self.colors = colors
+ N = len(colors)
+ else:
+ if isinstance(colors, str):
+ self.colors = [colors] * N
+ self.monochrome = True
+ elif np.iterable(colors):
+ if len(colors) == 1:
+ self.monochrome = True
+ self.colors = list(
+ itertools.islice(itertools.cycle(colors), N))
+ else:
+ try:
+ gray = float(colors)
+ except TypeError:
+ pass
+ else:
+ self.colors = [gray] * N
+ self.monochrome = True
+ super().__init__(name, N)
+
+ def _init(self):
+ self._lut = np.zeros((self.N + 3, 4), float)
+ self._lut[:-3] = to_rgba_array(self.colors)
+ self._isinit = True
+ self._set_extremes()
+
+ def resampled(self, lutsize):
+ """Return a new colormap with *lutsize* entries."""
+ colors = self(np.linspace(0, 1, lutsize))
+ new_cmap = ListedColormap(colors, name=self.name)
+ # Keep the over/under values too
+ new_cmap._rgba_over = self._rgba_over
+ new_cmap._rgba_under = self._rgba_under
+ new_cmap._rgba_bad = self._rgba_bad
+ return new_cmap
+
+ def reversed(self, name=None):
+ """
+ Return a reversed instance of the Colormap.
+
+ Parameters
+ ----------
+ name : str, optional
+ The name for the reversed colormap. If None, the
+ name is set to ``self.name + "_r"``.
+
+ Returns
+ -------
+ ListedColormap
+ A reversed instance of the colormap.
+ """
+ if name is None:
+ name = self.name + "_r"
+
+ colors_r = list(reversed(self.colors))
+ new_cmap = ListedColormap(colors_r, name=name, N=self.N)
+ # Reverse the over/under values too
+ new_cmap._rgba_over = self._rgba_under
+ new_cmap._rgba_under = self._rgba_over
+ new_cmap._rgba_bad = self._rgba_bad
+ return new_cmap
+
+
+class Normalize:
+ """
+ A class which, when called, linearly normalizes data into the
+ ``[0.0, 1.0]`` interval.
+ """
+
+ def __init__(self, vmin=None, vmax=None, clip=False):
+ """
+ Parameters
+ ----------
+ vmin, vmax : float or None
+ If *vmin* and/or *vmax* is not given, they are initialized from the
+ minimum and maximum value, respectively, of the first input
+ processed; i.e., ``__call__(A)`` calls ``autoscale_None(A)``.
+
+ clip : bool, default: False
+ If ``True`` values falling outside the range ``[vmin, vmax]``,
+ are mapped to 0 or 1, whichever is closer, and masked values are
+ set to 1. If ``False`` masked values remain masked.
+
+ Clipping silently defeats the purpose of setting the over, under,
+ and masked colors in a colormap, so it is likely to lead to
+ surprises; therefore the default is ``clip=False``.
+
+ Notes
+ -----
+ Returns 0 if ``vmin == vmax``.
+ """
+ self._vmin = _sanitize_extrema(vmin)
+ self._vmax = _sanitize_extrema(vmax)
+ self._clip = clip
+ self._scale = None
+ self.callbacks = cbook.CallbackRegistry(signals=["changed"])
+
+ @property
+ def vmin(self):
+ return self._vmin
+
+ @vmin.setter
+ def vmin(self, value):
+ value = _sanitize_extrema(value)
+ if value != self._vmin:
+ self._vmin = value
+ self._changed()
+
+ @property
+ def vmax(self):
+ return self._vmax
+
+ @vmax.setter
+ def vmax(self, value):
+ value = _sanitize_extrema(value)
+ if value != self._vmax:
+ self._vmax = value
+ self._changed()
+
+ @property
+ def clip(self):
+ return self._clip
+
+ @clip.setter
+ def clip(self, value):
+ if value != self._clip:
+ self._clip = value
+ self._changed()
+
+ def _changed(self):
+ """
+ Call this whenever the norm is changed to notify all the
+ callback listeners to the 'changed' signal.
+ """
+ self.callbacks.process('changed')
+
+ @staticmethod
+ def process_value(value):
+ """
+ Homogenize the input *value* for easy and efficient normalization.
+
+ *value* can be a scalar or sequence.
+
+ Returns
+ -------
+ result : masked array
+ Masked array with the same shape as *value*.
+ is_scalar : bool
+ Whether *value* is a scalar.
+
+ Notes
+ -----
+ Float dtypes are preserved; integer types with two bytes or smaller are
+ converted to np.float32, and larger types are converted to np.float64.
+ Preserving float32 when possible, and using in-place operations,
+ greatly improves speed for large arrays.
+ """
+ is_scalar = not np.iterable(value)
+ if is_scalar:
+ value = [value]
+ dtype = np.min_scalar_type(value)
+ if np.issubdtype(dtype, np.integer) or dtype.type is np.bool_:
+ # bool_/int8/int16 -> float32; int32/int64 -> float64
+ dtype = np.promote_types(dtype, np.float32)
+ # ensure data passed in as an ndarray subclass are interpreted as
+ # an ndarray. See issue #6622.
+ mask = np.ma.getmask(value)
+ data = np.asarray(value)
+ result = np.ma.array(data, mask=mask, dtype=dtype, copy=True)
+ return result, is_scalar
+
+ def __call__(self, value, clip=None):
+ """
+ Normalize *value* data in the ``[vmin, vmax]`` interval into the
+ ``[0.0, 1.0]`` interval and return it.
+
+ Parameters
+ ----------
+ value
+ Data to normalize.
+ clip : bool, optional
+ If ``None``, defaults to ``self.clip`` (which defaults to
+ ``False``).
+
+ Notes
+ -----
+ If not already initialized, ``self.vmin`` and ``self.vmax`` are
+ initialized using ``self.autoscale_None(value)``.
+ """
+ if clip is None:
+ clip = self.clip
+
+ result, is_scalar = self.process_value(value)
+
+ if self.vmin is None or self.vmax is None:
+ self.autoscale_None(result)
+ # Convert at least to float, without losing precision.
+ (vmin,), _ = self.process_value(self.vmin)
+ (vmax,), _ = self.process_value(self.vmax)
+ if vmin == vmax:
+ result.fill(0) # Or should it be all masked? Or 0.5?
+ elif vmin > vmax:
+ raise ValueError("minvalue must be less than or equal to maxvalue")
+ else:
+ if clip:
+ mask = np.ma.getmask(result)
+ result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax),
+ mask=mask)
+ # ma division is very slow; we can take a shortcut
+ resdat = result.data
+ resdat -= vmin
+ resdat /= (vmax - vmin)
+ result = np.ma.array(resdat, mask=result.mask, copy=False)
+ if is_scalar:
+ result = result[0]
+ return result
+
+ def inverse(self, value):
+ if not self.scaled():
+ raise ValueError("Not invertible until both vmin and vmax are set")
+ (vmin,), _ = self.process_value(self.vmin)
+ (vmax,), _ = self.process_value(self.vmax)
+
+ if np.iterable(value):
+ val = np.ma.asarray(value)
+ return vmin + val * (vmax - vmin)
+ else:
+ return vmin + value * (vmax - vmin)
+
+ def autoscale(self, A):
+ """Set *vmin*, *vmax* to min, max of *A*."""
+ with self.callbacks.blocked():
+ # Pause callbacks while we are updating so we only get
+ # a single update signal at the end
+ self.vmin = self.vmax = None
+ self.autoscale_None(A)
+ self._changed()
+
+ def autoscale_None(self, A):
+ """If vmin or vmax are not set, use the min/max of *A* to set them."""
+ A = np.asanyarray(A)
+ if self.vmin is None and A.size:
+ self.vmin = A.min()
+ if self.vmax is None and A.size:
+ self.vmax = A.max()
+
+ def scaled(self):
+ """Return whether vmin and vmax are set."""
+ return self.vmin is not None and self.vmax is not None
+
+
+class TwoSlopeNorm(Normalize):
+ def __init__(self, vcenter, vmin=None, vmax=None):
+ """
+ Normalize data with a set center.
+
+ Useful when mapping data with an unequal rates of change around a
+ conceptual center, e.g., data that range from -2 to 4, with 0 as
+ the midpoint.
+
+ Parameters
+ ----------
+ vcenter : float
+ The data value that defines ``0.5`` in the normalization.
+ vmin : float, optional
+ The data value that defines ``0.0`` in the normalization.
+ Defaults to the min value of the dataset.
+ vmax : float, optional
+ The data value that defines ``1.0`` in the normalization.
+ Defaults to the max value of the dataset.
+
+ Examples
+ --------
+ This maps data value -4000 to 0., 0 to 0.5, and +10000 to 1.0; data
+ between is linearly interpolated::
+
+ >>> import matplotlib.colors as mcolors
+ >>> offset = mcolors.TwoSlopeNorm(vmin=-4000.,
+ vcenter=0., vmax=10000)
+ >>> data = [-4000., -2000., 0., 2500., 5000., 7500., 10000.]
+ >>> offset(data)
+ array([0., 0.25, 0.5, 0.625, 0.75, 0.875, 1.0])
+ """
+
+ super().__init__(vmin=vmin, vmax=vmax)
+ self._vcenter = vcenter
+ if vcenter is not None and vmax is not None and vcenter >= vmax:
+ raise ValueError('vmin, vcenter, and vmax must be in '
+ 'ascending order')
+ if vcenter is not None and vmin is not None and vcenter <= vmin:
+ raise ValueError('vmin, vcenter, and vmax must be in '
+ 'ascending order')
+
+ @property
+ def vcenter(self):
+ return self._vcenter
+
+ @vcenter.setter
+ def vcenter(self, value):
+ if value != self._vcenter:
+ self._vcenter = value
+ self._changed()
+
+ def autoscale_None(self, A):
+ """
+ Get vmin and vmax, and then clip at vcenter
+ """
+ super().autoscale_None(A)
+ if self.vmin > self.vcenter:
+ self.vmin = self.vcenter
+ if self.vmax < self.vcenter:
+ self.vmax = self.vcenter
+
+ def __call__(self, value, clip=None):
+ """
+ Map value to the interval [0, 1]. The *clip* argument is unused.
+ """
+ result, is_scalar = self.process_value(value)
+ self.autoscale_None(result) # sets self.vmin, self.vmax if None
+
+ if not self.vmin <= self.vcenter <= self.vmax:
+ raise ValueError("vmin, vcenter, vmax must increase monotonically")
+ # note that we must extrapolate for tick locators:
+ result = np.ma.masked_array(
+ np.interp(result, [self.vmin, self.vcenter, self.vmax],
+ [0, 0.5, 1], left=-np.inf, right=np.inf),
+ mask=np.ma.getmask(result))
+ if is_scalar:
+ result = np.atleast_1d(result)[0]
+ return result
+
+ def inverse(self, value):
+ if not self.scaled():
+ raise ValueError("Not invertible until both vmin and vmax are set")
+ (vmin,), _ = self.process_value(self.vmin)
+ (vmax,), _ = self.process_value(self.vmax)
+ (vcenter,), _ = self.process_value(self.vcenter)
+ result = np.interp(value, [0, 0.5, 1], [vmin, vcenter, vmax],
+ left=-np.inf, right=np.inf)
+ return result
+
+
+class CenteredNorm(Normalize):
+ def __init__(self, vcenter=0, halfrange=None, clip=False):
+ """
+ Normalize symmetrical data around a center (0 by default).
+
+ Unlike `TwoSlopeNorm`, `CenteredNorm` applies an equal rate of change
+ around the center.
+
+ Useful when mapping symmetrical data around a conceptual center
+ e.g., data that range from -2 to 4, with 0 as the midpoint, and
+ with equal rates of change around that midpoint.
+
+ Parameters
+ ----------
+ vcenter : float, default: 0
+ The data value that defines ``0.5`` in the normalization.
+ halfrange : float, optional
+ The range of data values that defines a range of ``0.5`` in the
+ normalization, so that *vcenter* - *halfrange* is ``0.0`` and
+ *vcenter* + *halfrange* is ``1.0`` in the normalization.
+ Defaults to the largest absolute difference to *vcenter* for
+ the values in the dataset.
+ clip : bool, default: False
+ If ``True`` values falling outside the range ``[vmin, vmax]``,
+ are mapped to 0 or 1, whichever is closer, and masked values are
+ set to 1. If ``False`` masked values remain masked.
+
+ Examples
+ --------
+ This maps data values -2 to 0.25, 0 to 0.5, and 4 to 1.0
+ (assuming equal rates of change above and below 0.0):
+
+ >>> import matplotlib.colors as mcolors
+ >>> norm = mcolors.CenteredNorm(halfrange=4.0)
+ >>> data = [-2., 0., 4.]
+ >>> norm(data)
+ array([0.25, 0.5 , 1. ])
+ """
+ super().__init__(vmin=None, vmax=None, clip=clip)
+ self._vcenter = vcenter
+ # calling the halfrange setter to set vmin and vmax
+ self.halfrange = halfrange
+
+ def autoscale(self, A):
+ """
+ Set *halfrange* to ``max(abs(A-vcenter))``, then set *vmin* and *vmax*.
+ """
+ A = np.asanyarray(A)
+ self.halfrange = max(self._vcenter-A.min(),
+ A.max()-self._vcenter)
+
+ def autoscale_None(self, A):
+ """Set *vmin* and *vmax*."""
+ A = np.asanyarray(A)
+ if self.halfrange is None and A.size:
+ self.autoscale(A)
+
+ @property
+ def vmin(self):
+ return self._vmin
+
+ @vmin.setter
+ def vmin(self, value):
+ value = _sanitize_extrema(value)
+ if value != self._vmin:
+ self._vmin = value
+ self._vmax = 2*self.vcenter - value
+ self._changed()
+
+ @property
+ def vmax(self):
+ return self._vmax
+
+ @vmax.setter
+ def vmax(self, value):
+ value = _sanitize_extrema(value)
+ if value != self._vmax:
+ self._vmax = value
+ self._vmin = 2*self.vcenter - value
+ self._changed()
+
+ @property
+ def vcenter(self):
+ return self._vcenter
+
+ @vcenter.setter
+ def vcenter(self, vcenter):
+ if vcenter != self._vcenter:
+ self._vcenter = vcenter
+ # Trigger an update of the vmin/vmax values through the setter
+ self.halfrange = self.halfrange
+ self._changed()
+
+ @property
+ def halfrange(self):
+ if self.vmin is None or self.vmax is None:
+ return None
+ return (self.vmax - self.vmin) / 2
+
+ @halfrange.setter
+ def halfrange(self, halfrange):
+ if halfrange is None:
+ self.vmin = None
+ self.vmax = None
+ else:
+ self.vmin = self.vcenter - abs(halfrange)
+ self.vmax = self.vcenter + abs(halfrange)
+
+
+def make_norm_from_scale(scale_cls, base_norm_cls=None, *, init=None):
+ """
+ Decorator for building a `.Normalize` subclass from a `~.scale.ScaleBase`
+ subclass.
+
+ After ::
+
+ @make_norm_from_scale(scale_cls)
+ class norm_cls(Normalize):
+ ...
+
+ *norm_cls* is filled with methods so that normalization computations are
+ forwarded to *scale_cls* (i.e., *scale_cls* is the scale that would be used
+ for the colorbar of a mappable normalized with *norm_cls*).
+
+ If *init* is not passed, then the constructor signature of *norm_cls*
+ will be ``norm_cls(vmin=None, vmax=None, clip=False)``; these three
+ parameters will be forwarded to the base class (``Normalize.__init__``),
+ and a *scale_cls* object will be initialized with no arguments (other than
+ a dummy axis).
+
+ If the *scale_cls* constructor takes additional parameters, then *init*
+ should be passed to `make_norm_from_scale`. It is a callable which is
+ *only* used for its signature. First, this signature will become the
+ signature of *norm_cls*. Second, the *norm_cls* constructor will bind the
+ parameters passed to it using this signature, extract the bound *vmin*,
+ *vmax*, and *clip* values, pass those to ``Normalize.__init__``, and
+ forward the remaining bound values (including any defaults defined by the
+ signature) to the *scale_cls* constructor.
+ """
+
+ if base_norm_cls is None:
+ return functools.partial(make_norm_from_scale, scale_cls, init=init)
+
+ if isinstance(scale_cls, functools.partial):
+ scale_args = scale_cls.args
+ scale_kwargs_items = tuple(scale_cls.keywords.items())
+ scale_cls = scale_cls.func
+ else:
+ scale_args = scale_kwargs_items = ()
+
+ if init is None:
+ def init(vmin=None, vmax=None, clip=False): pass
+
+ return _make_norm_from_scale(
+ scale_cls, scale_args, scale_kwargs_items,
+ base_norm_cls, inspect.signature(init))
+
+
+@functools.lru_cache(None)
+def _make_norm_from_scale(
+ scale_cls, scale_args, scale_kwargs_items,
+ base_norm_cls, bound_init_signature,
+):
+ """
+ Helper for `make_norm_from_scale`.
+
+ This function is split out to enable caching (in particular so that
+ different unpickles reuse the same class). In order to do so,
+
+ - ``functools.partial`` *scale_cls* is expanded into ``func, args, kwargs``
+ to allow memoizing returned norms (partial instances always compare
+ unequal, but we can check identity based on ``func, args, kwargs``;
+ - *init* is replaced by *init_signature*, as signatures are picklable,
+ unlike to arbitrary lambdas.
+ """
+
+ class Norm(base_norm_cls):
+ def __reduce__(self):
+ cls = type(self)
+ # If the class is toplevel-accessible, it is possible to directly
+ # pickle it "by name". This is required to support norm classes
+ # defined at a module's toplevel, as the inner base_norm_cls is
+ # otherwise unpicklable (as it gets shadowed by the generated norm
+ # class). If either import or attribute access fails, fall back to
+ # the general path.
+ try:
+ if cls is getattr(importlib.import_module(cls.__module__),
+ cls.__qualname__):
+ return (_create_empty_object_of_class, (cls,), vars(self))
+ except (ImportError, AttributeError):
+ pass
+ return (_picklable_norm_constructor,
+ (scale_cls, scale_args, scale_kwargs_items,
+ base_norm_cls, bound_init_signature),
+ vars(self))
+
+ def __init__(self, *args, **kwargs):
+ ba = bound_init_signature.bind(*args, **kwargs)
+ ba.apply_defaults()
+ super().__init__(
+ **{k: ba.arguments.pop(k) for k in ["vmin", "vmax", "clip"]})
+ self._scale = functools.partial(
+ scale_cls, *scale_args, **dict(scale_kwargs_items))(
+ axis=None, **ba.arguments)
+ self._trf = self._scale.get_transform()
+
+ __init__.__signature__ = bound_init_signature.replace(parameters=[
+ inspect.Parameter("self", inspect.Parameter.POSITIONAL_OR_KEYWORD),
+ *bound_init_signature.parameters.values()])
+
+ def __call__(self, value, clip=None):
+ value, is_scalar = self.process_value(value)
+ if self.vmin is None or self.vmax is None:
+ self.autoscale_None(value)
+ if self.vmin > self.vmax:
+ raise ValueError("vmin must be less or equal to vmax")
+ if self.vmin == self.vmax:
+ return np.full_like(value, 0)
+ if clip is None:
+ clip = self.clip
+ if clip:
+ value = np.clip(value, self.vmin, self.vmax)
+ t_value = self._trf.transform(value).reshape(np.shape(value))
+ t_vmin, t_vmax = self._trf.transform([self.vmin, self.vmax])
+ if not np.isfinite([t_vmin, t_vmax]).all():
+ raise ValueError("Invalid vmin or vmax")
+ t_value -= t_vmin
+ t_value /= (t_vmax - t_vmin)
+ t_value = np.ma.masked_invalid(t_value, copy=False)
+ return t_value[0] if is_scalar else t_value
+
+ def inverse(self, value):
+ if not self.scaled():
+ raise ValueError("Not invertible until scaled")
+ if self.vmin > self.vmax:
+ raise ValueError("vmin must be less or equal to vmax")
+ t_vmin, t_vmax = self._trf.transform([self.vmin, self.vmax])
+ if not np.isfinite([t_vmin, t_vmax]).all():
+ raise ValueError("Invalid vmin or vmax")
+ value, is_scalar = self.process_value(value)
+ rescaled = value * (t_vmax - t_vmin)
+ rescaled += t_vmin
+ value = (self._trf
+ .inverted()
+ .transform(rescaled)
+ .reshape(np.shape(value)))
+ return value[0] if is_scalar else value
+
+ def autoscale_None(self, A):
+ # i.e. A[np.isfinite(...)], but also for non-array A's
+ in_trf_domain = np.extract(np.isfinite(self._trf.transform(A)), A)
+ if in_trf_domain.size == 0:
+ in_trf_domain = np.ma.masked
+ return super().autoscale_None(in_trf_domain)
+
+ if base_norm_cls is Normalize:
+ Norm.__name__ = f"{scale_cls.__name__}Norm"
+ Norm.__qualname__ = f"{scale_cls.__qualname__}Norm"
+ else:
+ Norm.__name__ = base_norm_cls.__name__
+ Norm.__qualname__ = base_norm_cls.__qualname__
+ Norm.__module__ = base_norm_cls.__module__
+ Norm.__doc__ = base_norm_cls.__doc__
+
+ return Norm
+
+
+def _create_empty_object_of_class(cls):
+ return cls.__new__(cls)
+
+
+def _picklable_norm_constructor(*args):
+ return _create_empty_object_of_class(_make_norm_from_scale(*args))
+
+
+@make_norm_from_scale(
+ scale.FuncScale,
+ init=lambda functions, vmin=None, vmax=None, clip=False: None)
+class FuncNorm(Normalize):
+ """
+ Arbitrary normalization using functions for the forward and inverse.
+
+ Parameters
+ ----------
+ functions : (callable, callable)
+ two-tuple of the forward and inverse functions for the normalization.
+ The forward function must be monotonic.
+
+ Both functions must have the signature ::
+
+ def forward(values: array-like) -> array-like
+
+ vmin, vmax : float or None
+ If *vmin* and/or *vmax* is not given, they are initialized from the
+ minimum and maximum value, respectively, of the first input
+ processed; i.e., ``__call__(A)`` calls ``autoscale_None(A)``.
+
+ clip : bool, default: False
+ If ``True`` values falling outside the range ``[vmin, vmax]``,
+ are mapped to 0 or 1, whichever is closer, and masked values are
+ set to 1. If ``False`` masked values remain masked.
+
+ Clipping silently defeats the purpose of setting the over, under,
+ and masked colors in a colormap, so it is likely to lead to
+ surprises; therefore the default is ``clip=False``.
+ """
+
+
+LogNorm = make_norm_from_scale(
+ functools.partial(scale.LogScale, nonpositive="mask"))(Normalize)
+LogNorm.__name__ = LogNorm.__qualname__ = "LogNorm"
+LogNorm.__doc__ = "Normalize a given value to the 0-1 range on a log scale."
+
+
+@make_norm_from_scale(
+ scale.SymmetricalLogScale,
+ init=lambda linthresh, linscale=1., vmin=None, vmax=None, clip=False, *,
+ base=10: None)
+class SymLogNorm(Normalize):
+ """
+ The symmetrical logarithmic scale is logarithmic in both the
+ positive and negative directions from the origin.
+
+ Since the values close to zero tend toward infinity, there is a
+ need to have a range around zero that is linear. The parameter
+ *linthresh* allows the user to specify the size of this range
+ (-*linthresh*, *linthresh*).
+
+ Parameters
+ ----------
+ linthresh : float
+ The range within which the plot is linear (to avoid having the plot
+ go to infinity around zero).
+ linscale : float, default: 1
+ This allows the linear range (-*linthresh* to *linthresh*) to be
+ stretched relative to the logarithmic range. Its value is the
+ number of decades to use for each half of the linear range. For
+ example, when *linscale* == 1.0 (the default), the space used for
+ the positive and negative halves of the linear range will be equal
+ to one decade in the logarithmic range.
+ base : float, default: 10
+ """
+
+ @property
+ def linthresh(self):
+ return self._scale.linthresh
+
+ @linthresh.setter
+ def linthresh(self, value):
+ self._scale.linthresh = value
+
+
+@make_norm_from_scale(
+ scale.AsinhScale,
+ init=lambda linear_width=1, vmin=None, vmax=None, clip=False: None)
+class AsinhNorm(Normalize):
+ """
+ The inverse hyperbolic sine scale is approximately linear near
+ the origin, but becomes logarithmic for larger positive
+ or negative values. Unlike the `SymLogNorm`, the transition between
+ these linear and logarithmic regions is smooth, which may reduce
+ the risk of visual artifacts.
+
+ .. note::
+
+ This API is provisional and may be revised in the future
+ based on early user feedback.
+
+ Parameters
+ ----------
+ linear_width : float, default: 1
+ The effective width of the linear region, beyond which
+ the transformation becomes asymptotically logarithmic
+ """
+
+ @property
+ def linear_width(self):
+ return self._scale.linear_width
+
+ @linear_width.setter
+ def linear_width(self, value):
+ self._scale.linear_width = value
+
+
+class PowerNorm(Normalize):
+ """
+ Linearly map a given value to the 0-1 range and then apply
+ a power-law normalization over that range.
+ """
+ def __init__(self, gamma, vmin=None, vmax=None, clip=False):
+ super().__init__(vmin, vmax, clip)
+ self.gamma = gamma
+
+ def __call__(self, value, clip=None):
+ if clip is None:
+ clip = self.clip
+
+ result, is_scalar = self.process_value(value)
+
+ self.autoscale_None(result)
+ gamma = self.gamma
+ vmin, vmax = self.vmin, self.vmax
+ if vmin > vmax:
+ raise ValueError("minvalue must be less than or equal to maxvalue")
+ elif vmin == vmax:
+ result.fill(0)
+ else:
+ if clip:
+ mask = np.ma.getmask(result)
+ result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax),
+ mask=mask)
+ resdat = result.data
+ resdat -= vmin
+ resdat[resdat < 0] = 0
+ np.power(resdat, gamma, resdat)
+ resdat /= (vmax - vmin) ** gamma
+
+ result = np.ma.array(resdat, mask=result.mask, copy=False)
+ if is_scalar:
+ result = result[0]
+ return result
+
+ def inverse(self, value):
+ if not self.scaled():
+ raise ValueError("Not invertible until scaled")
+ gamma = self.gamma
+ vmin, vmax = self.vmin, self.vmax
+
+ if np.iterable(value):
+ val = np.ma.asarray(value)
+ return np.ma.power(val, 1. / gamma) * (vmax - vmin) + vmin
+ else:
+ return pow(value, 1. / gamma) * (vmax - vmin) + vmin
+
+
+class BoundaryNorm(Normalize):
+ """
+ Generate a colormap index based on discrete intervals.
+
+ Unlike `Normalize` or `LogNorm`, `BoundaryNorm` maps values to integers
+ instead of to the interval 0-1.
+ """
+
+ # Mapping to the 0-1 interval could have been done via piece-wise linear
+ # interpolation, but using integers seems simpler, and reduces the number
+ # of conversions back and forth between int and float.
+
+ def __init__(self, boundaries, ncolors, clip=False, *, extend='neither'):
+ """
+ Parameters
+ ----------
+ boundaries : array-like
+ Monotonically increasing sequence of at least 2 bin edges: data
+ falling in the n-th bin will be mapped to the n-th color.
+
+ ncolors : int
+ Number of colors in the colormap to be used.
+
+ clip : bool, optional
+ If clip is ``True``, out of range values are mapped to 0 if they
+ are below ``boundaries[0]`` or mapped to ``ncolors - 1`` if they
+ are above ``boundaries[-1]``.
+
+ If clip is ``False``, out of range values are mapped to -1 if
+ they are below ``boundaries[0]`` or mapped to *ncolors* if they are
+ above ``boundaries[-1]``. These are then converted to valid indices
+ by `Colormap.__call__`.
+
+ extend : {'neither', 'both', 'min', 'max'}, default: 'neither'
+ Extend the number of bins to include one or both of the
+ regions beyond the boundaries. For example, if ``extend``
+ is 'min', then the color to which the region between the first
+ pair of boundaries is mapped will be distinct from the first
+ color in the colormap, and by default a
+ `~matplotlib.colorbar.Colorbar` will be drawn with
+ the triangle extension on the left or lower end.
+
+ Notes
+ -----
+ If there are fewer bins (including extensions) than colors, then the
+ color index is chosen by linearly interpolating the ``[0, nbins - 1]``
+ range onto the ``[0, ncolors - 1]`` range, effectively skipping some
+ colors in the middle of the colormap.
+ """
+ if clip and extend != 'neither':
+ raise ValueError("'clip=True' is not compatible with 'extend'")
+ super().__init__(vmin=boundaries[0], vmax=boundaries[-1], clip=clip)
+ self.boundaries = np.asarray(boundaries)
+ self.N = len(self.boundaries)
+ if self.N < 2:
+ raise ValueError("You must provide at least 2 boundaries "
+ f"(1 region) but you passed in {boundaries!r}")
+ self.Ncmap = ncolors
+ self.extend = extend
+
+ self._scale = None # don't use the default scale.
+
+ self._n_regions = self.N - 1 # number of colors needed
+ self._offset = 0
+ if extend in ('min', 'both'):
+ self._n_regions += 1
+ self._offset = 1
+ if extend in ('max', 'both'):
+ self._n_regions += 1
+ if self._n_regions > self.Ncmap:
+ raise ValueError(f"There are {self._n_regions} color bins "
+ "including extensions, but ncolors = "
+ f"{ncolors}; ncolors must equal or exceed the "
+ "number of bins")
+
+ def __call__(self, value, clip=None):
+ """
+ This method behaves similarly to `.Normalize.__call__`, except that it
+ returns integers or arrays of int16.
+ """
+ if clip is None:
+ clip = self.clip
+
+ xx, is_scalar = self.process_value(value)
+ mask = np.ma.getmaskarray(xx)
+ # Fill masked values a value above the upper boundary
+ xx = np.atleast_1d(xx.filled(self.vmax + 1))
+ if clip:
+ np.clip(xx, self.vmin, self.vmax, out=xx)
+ max_col = self.Ncmap - 1
+ else:
+ max_col = self.Ncmap
+ # this gives us the bins in the lookup table in the range
+ # [0, _n_regions - 1] (the offset is set in the init)
+ iret = np.digitize(xx, self.boundaries) - 1 + self._offset
+ # if we have more colors than regions, stretch the region
+ # index computed above to full range of the color bins. This
+ # will make use of the full range (but skip some of the colors
+ # in the middle) such that the first region is mapped to the
+ # first color and the last region is mapped to the last color.
+ if self.Ncmap > self._n_regions:
+ if self._n_regions == 1:
+ # special case the 1 region case, pick the middle color
+ iret[iret == 0] = (self.Ncmap - 1) // 2
+ else:
+ # otherwise linearly remap the values from the region index
+ # to the color index spaces
+ iret = (self.Ncmap - 1) / (self._n_regions - 1) * iret
+ # cast to 16bit integers in all cases
+ iret = iret.astype(np.int16)
+ iret[xx < self.vmin] = -1
+ iret[xx >= self.vmax] = max_col
+ ret = np.ma.array(iret, mask=mask)
+ if is_scalar:
+ ret = int(ret[0]) # assume python scalar
+ return ret
+
+ def inverse(self, value):
+ """
+ Raises
+ ------
+ ValueError
+ BoundaryNorm is not invertible, so calling this method will always
+ raise an error
+ """
+ raise ValueError("BoundaryNorm is not invertible")
+
+
+class NoNorm(Normalize):
+ """
+ Dummy replacement for `Normalize`, for the case where we want to use
+ indices directly in a `~matplotlib.cm.ScalarMappable`.
+ """
+ def __call__(self, value, clip=None):
+ return value
+
+ def inverse(self, value):
+ return value
+
+
+def rgb_to_hsv(arr):
+ """
+ Convert float RGB values (in the range [0, 1]), in a numpy array to HSV
+ values.
+
+ Parameters
+ ----------
+ arr : (..., 3) array-like
+ All values must be in the range [0, 1]
+
+ Returns
+ -------
+ (..., 3) `~numpy.ndarray`
+ Colors converted to HSV values in range [0, 1]
+ """
+ arr = np.asarray(arr)
+
+ # check length of the last dimension, should be _some_ sort of rgb
+ if arr.shape[-1] != 3:
+ raise ValueError("Last dimension of input array must be 3; "
+ "shape {} was found.".format(arr.shape))
+
+ in_shape = arr.shape
+ arr = np.array(
+ arr, copy=False,
+ dtype=np.promote_types(arr.dtype, np.float32), # Don't work on ints.
+ ndmin=2, # In case input was 1D.
+ )
+ out = np.zeros_like(arr)
+ arr_max = arr.max(-1)
+ ipos = arr_max > 0
+ delta = arr.ptp(-1)
+ s = np.zeros_like(delta)
+ s[ipos] = delta[ipos] / arr_max[ipos]
+ ipos = delta > 0
+ # red is max
+ idx = (arr[..., 0] == arr_max) & ipos
+ out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx]
+ # green is max
+ idx = (arr[..., 1] == arr_max) & ipos
+ out[idx, 0] = 2. + (arr[idx, 2] - arr[idx, 0]) / delta[idx]
+ # blue is max
+ idx = (arr[..., 2] == arr_max) & ipos
+ out[idx, 0] = 4. + (arr[idx, 0] - arr[idx, 1]) / delta[idx]
+
+ out[..., 0] = (out[..., 0] / 6.0) % 1.0
+ out[..., 1] = s
+ out[..., 2] = arr_max
+
+ return out.reshape(in_shape)
+
+
+def hsv_to_rgb(hsv):
+ """
+ Convert HSV values to RGB.
+
+ Parameters
+ ----------
+ hsv : (..., 3) array-like
+ All values assumed to be in range [0, 1]
+
+ Returns
+ -------
+ (..., 3) `~numpy.ndarray`
+ Colors converted to RGB values in range [0, 1]
+ """
+ hsv = np.asarray(hsv)
+
+ # check length of the last dimension, should be _some_ sort of rgb
+ if hsv.shape[-1] != 3:
+ raise ValueError("Last dimension of input array must be 3; "
+ "shape {shp} was found.".format(shp=hsv.shape))
+
+ in_shape = hsv.shape
+ hsv = np.array(
+ hsv, copy=False,
+ dtype=np.promote_types(hsv.dtype, np.float32), # Don't work on ints.
+ ndmin=2, # In case input was 1D.
+ )
+
+ h = hsv[..., 0]
+ s = hsv[..., 1]
+ v = hsv[..., 2]
+
+ r = np.empty_like(h)
+ g = np.empty_like(h)
+ b = np.empty_like(h)
+
+ i = (h * 6.0).astype(int)
+ f = (h * 6.0) - i
+ p = v * (1.0 - s)
+ q = v * (1.0 - s * f)
+ t = v * (1.0 - s * (1.0 - f))
+
+ idx = i % 6 == 0
+ r[idx] = v[idx]
+ g[idx] = t[idx]
+ b[idx] = p[idx]
+
+ idx = i == 1
+ r[idx] = q[idx]
+ g[idx] = v[idx]
+ b[idx] = p[idx]
+
+ idx = i == 2
+ r[idx] = p[idx]
+ g[idx] = v[idx]
+ b[idx] = t[idx]
+
+ idx = i == 3
+ r[idx] = p[idx]
+ g[idx] = q[idx]
+ b[idx] = v[idx]
+
+ idx = i == 4
+ r[idx] = t[idx]
+ g[idx] = p[idx]
+ b[idx] = v[idx]
+
+ idx = i == 5
+ r[idx] = v[idx]
+ g[idx] = p[idx]
+ b[idx] = q[idx]
+
+ idx = s == 0
+ r[idx] = v[idx]
+ g[idx] = v[idx]
+ b[idx] = v[idx]
+
+ rgb = np.stack([r, g, b], axis=-1)
+
+ return rgb.reshape(in_shape)
+
+
+def _vector_magnitude(arr):
+ # things that don't work here:
+ # * np.linalg.norm: drops mask from ma.array
+ # * np.sum: drops mask from ma.array unless entire vector is masked
+ sum_sq = 0
+ for i in range(arr.shape[-1]):
+ sum_sq += arr[..., i, np.newaxis] ** 2
+ return np.sqrt(sum_sq)
+
+
+class LightSource:
+ """
+ Create a light source coming from the specified azimuth and elevation.
+ Angles are in degrees, with the azimuth measured
+ clockwise from north and elevation up from the zero plane of the surface.
+
+ `shade` is used to produce "shaded" RGB values for a data array.
+ `shade_rgb` can be used to combine an RGB image with an elevation map.
+ `hillshade` produces an illumination map of a surface.
+ """
+
+ def __init__(self, azdeg=315, altdeg=45, hsv_min_val=0, hsv_max_val=1,
+ hsv_min_sat=1, hsv_max_sat=0):
+ """
+ Specify the azimuth (measured clockwise from south) and altitude
+ (measured up from the plane of the surface) of the light source
+ in degrees.
+
+ Parameters
+ ----------
+ azdeg : float, default: 315 degrees (from the northwest)
+ The azimuth (0-360, degrees clockwise from North) of the light
+ source.
+ altdeg : float, default: 45 degrees
+ The altitude (0-90, degrees up from horizontal) of the light
+ source.
+
+ Notes
+ -----
+ For backwards compatibility, the parameters *hsv_min_val*,
+ *hsv_max_val*, *hsv_min_sat*, and *hsv_max_sat* may be supplied at
+ initialization as well. However, these parameters will only be used if
+ "blend_mode='hsv'" is passed into `shade` or `shade_rgb`.
+ See the documentation for `blend_hsv` for more details.
+ """
+ self.azdeg = azdeg
+ self.altdeg = altdeg
+ self.hsv_min_val = hsv_min_val
+ self.hsv_max_val = hsv_max_val
+ self.hsv_min_sat = hsv_min_sat
+ self.hsv_max_sat = hsv_max_sat
+
+ @property
+ def direction(self):
+ """The unit vector direction towards the light source."""
+ # Azimuth is in degrees clockwise from North. Convert to radians
+ # counterclockwise from East (mathematical notation).
+ az = np.radians(90 - self.azdeg)
+ alt = np.radians(self.altdeg)
+ return np.array([
+ np.cos(az) * np.cos(alt),
+ np.sin(az) * np.cos(alt),
+ np.sin(alt)
+ ])
+
+ def hillshade(self, elevation, vert_exag=1, dx=1, dy=1, fraction=1.):
+ """
+ Calculate the illumination intensity for a surface using the defined
+ azimuth and elevation for the light source.
+
+ This computes the normal vectors for the surface, and then passes them
+ on to `shade_normals`
+
+ Parameters
+ ----------
+ elevation : 2D array-like
+ The height values used to generate an illumination map
+ vert_exag : number, optional
+ The amount to exaggerate the elevation values by when calculating
+ illumination. This can be used either to correct for differences in
+ units between the x-y coordinate system and the elevation
+ coordinate system (e.g. decimal degrees vs. meters) or to
+ exaggerate or de-emphasize topographic effects.
+ dx : number, optional
+ The x-spacing (columns) of the input *elevation* grid.
+ dy : number, optional
+ The y-spacing (rows) of the input *elevation* grid.
+ fraction : number, optional
+ Increases or decreases the contrast of the hillshade. Values
+ greater than one will cause intermediate values to move closer to
+ full illumination or shadow (and clipping any values that move
+ beyond 0 or 1). Note that this is not visually or mathematically
+ the same as vertical exaggeration.
+
+ Returns
+ -------
+ `~numpy.ndarray`
+ A 2D array of illumination values between 0-1, where 0 is
+ completely in shadow and 1 is completely illuminated.
+ """
+
+ # Because most image and raster GIS data has the first row in the array
+ # as the "top" of the image, dy is implicitly negative. This is
+ # consistent to what `imshow` assumes, as well.
+ dy = -dy
+
+ # compute the normal vectors from the partial derivatives
+ e_dy, e_dx = np.gradient(vert_exag * elevation, dy, dx)
+
+ # .view is to keep subclasses
+ normal = np.empty(elevation.shape + (3,)).view(type(elevation))
+ normal[..., 0] = -e_dx
+ normal[..., 1] = -e_dy
+ normal[..., 2] = 1
+ normal /= _vector_magnitude(normal)
+
+ return self.shade_normals(normal, fraction)
+
+ def shade_normals(self, normals, fraction=1.):
+ """
+ Calculate the illumination intensity for the normal vectors of a
+ surface using the defined azimuth and elevation for the light source.
+
+ Imagine an artificial sun placed at infinity in some azimuth and
+ elevation position illuminating our surface. The parts of the surface
+ that slope toward the sun should brighten while those sides facing away
+ should become darker.
+
+ Parameters
+ ----------
+ fraction : number, optional
+ Increases or decreases the contrast of the hillshade. Values
+ greater than one will cause intermediate values to move closer to
+ full illumination or shadow (and clipping any values that move
+ beyond 0 or 1). Note that this is not visually or mathematically
+ the same as vertical exaggeration.
+
+ Returns
+ -------
+ `~numpy.ndarray`
+ A 2D array of illumination values between 0-1, where 0 is
+ completely in shadow and 1 is completely illuminated.
+ """
+
+ intensity = normals.dot(self.direction)
+
+ # Apply contrast stretch
+ imin, imax = intensity.min(), intensity.max()
+ intensity *= fraction
+
+ # Rescale to 0-1, keeping range before contrast stretch
+ # If constant slope, keep relative scaling (i.e. flat should be 0.5,
+ # fully occluded 0, etc.)
+ if (imax - imin) > 1e-6:
+ # Strictly speaking, this is incorrect. Negative values should be
+ # clipped to 0 because they're fully occluded. However, rescaling
+ # in this manner is consistent with the previous implementation and
+ # visually appears better than a "hard" clip.
+ intensity -= imin
+ intensity /= (imax - imin)
+ intensity = np.clip(intensity, 0, 1)
+
+ return intensity
+
+ def shade(self, data, cmap, norm=None, blend_mode='overlay', vmin=None,
+ vmax=None, vert_exag=1, dx=1, dy=1, fraction=1, **kwargs):
+ """
+ Combine colormapped data values with an illumination intensity map
+ (a.k.a. "hillshade") of the values.
+
+ Parameters
+ ----------
+ data : 2D array-like
+ The height values used to generate a shaded map.
+ cmap : `~matplotlib.colors.Colormap`
+ The colormap used to color the *data* array. Note that this must be
+ a `~matplotlib.colors.Colormap` instance. For example, rather than
+ passing in ``cmap='gist_earth'``, use
+ ``cmap=plt.get_cmap('gist_earth')`` instead.
+ norm : `~matplotlib.colors.Normalize` instance, optional
+ The normalization used to scale values before colormapping. If
+ None, the input will be linearly scaled between its min and max.
+ blend_mode : {'hsv', 'overlay', 'soft'} or callable, optional
+ The type of blending used to combine the colormapped data
+ values with the illumination intensity. Default is
+ "overlay". Note that for most topographic surfaces,
+ "overlay" or "soft" appear more visually realistic. If a
+ user-defined function is supplied, it is expected to
+ combine an MxNx3 RGB array of floats (ranging 0 to 1) with
+ an MxNx1 hillshade array (also 0 to 1). (Call signature
+ ``func(rgb, illum, **kwargs)``) Additional kwargs supplied
+ to this function will be passed on to the *blend_mode*
+ function.
+ vmin : float or None, optional
+ The minimum value used in colormapping *data*. If *None* the
+ minimum value in *data* is used. If *norm* is specified, then this
+ argument will be ignored.
+ vmax : float or None, optional
+ The maximum value used in colormapping *data*. If *None* the
+ maximum value in *data* is used. If *norm* is specified, then this
+ argument will be ignored.
+ vert_exag : number, optional
+ The amount to exaggerate the elevation values by when calculating
+ illumination. This can be used either to correct for differences in
+ units between the x-y coordinate system and the elevation
+ coordinate system (e.g. decimal degrees vs. meters) or to
+ exaggerate or de-emphasize topography.
+ dx : number, optional
+ The x-spacing (columns) of the input *elevation* grid.
+ dy : number, optional
+ The y-spacing (rows) of the input *elevation* grid.
+ fraction : number, optional
+ Increases or decreases the contrast of the hillshade. Values
+ greater than one will cause intermediate values to move closer to
+ full illumination or shadow (and clipping any values that move
+ beyond 0 or 1). Note that this is not visually or mathematically
+ the same as vertical exaggeration.
+ **kwargs
+ Additional kwargs are passed on to the *blend_mode* function.
+
+ Returns
+ -------
+ `~numpy.ndarray`
+ An MxNx4 array of floats ranging between 0-1.
+ """
+ if vmin is None:
+ vmin = data.min()
+ if vmax is None:
+ vmax = data.max()
+ if norm is None:
+ norm = Normalize(vmin=vmin, vmax=vmax)
+
+ rgb0 = cmap(norm(data))
+ rgb1 = self.shade_rgb(rgb0, elevation=data, blend_mode=blend_mode,
+ vert_exag=vert_exag, dx=dx, dy=dy,
+ fraction=fraction, **kwargs)
+ # Don't overwrite the alpha channel, if present.
+ rgb0[..., :3] = rgb1[..., :3]
+ return rgb0
+
+ def shade_rgb(self, rgb, elevation, fraction=1., blend_mode='hsv',
+ vert_exag=1, dx=1, dy=1, **kwargs):
+ """
+ Use this light source to adjust the colors of the *rgb* input array to
+ give the impression of a shaded relief map with the given *elevation*.
+
+ Parameters
+ ----------
+ rgb : array-like
+ An (M, N, 3) RGB array, assumed to be in the range of 0 to 1.
+ elevation : array-like
+ An (M, N) array of the height values used to generate a shaded map.
+ fraction : number
+ Increases or decreases the contrast of the hillshade. Values
+ greater than one will cause intermediate values to move closer to
+ full illumination or shadow (and clipping any values that move
+ beyond 0 or 1). Note that this is not visually or mathematically
+ the same as vertical exaggeration.
+ blend_mode : {'hsv', 'overlay', 'soft'} or callable, optional
+ The type of blending used to combine the colormapped data values
+ with the illumination intensity. For backwards compatibility, this
+ defaults to "hsv". Note that for most topographic surfaces,
+ "overlay" or "soft" appear more visually realistic. If a
+ user-defined function is supplied, it is expected to combine an
+ MxNx3 RGB array of floats (ranging 0 to 1) with an MxNx1 hillshade
+ array (also 0 to 1). (Call signature
+ ``func(rgb, illum, **kwargs)``)
+ Additional kwargs supplied to this function will be passed on to
+ the *blend_mode* function.
+ vert_exag : number, optional
+ The amount to exaggerate the elevation values by when calculating
+ illumination. This can be used either to correct for differences in
+ units between the x-y coordinate system and the elevation
+ coordinate system (e.g. decimal degrees vs. meters) or to
+ exaggerate or de-emphasize topography.
+ dx : number, optional
+ The x-spacing (columns) of the input *elevation* grid.
+ dy : number, optional
+ The y-spacing (rows) of the input *elevation* grid.
+ **kwargs
+ Additional kwargs are passed on to the *blend_mode* function.
+
+ Returns
+ -------
+ `~numpy.ndarray`
+ An (m, n, 3) array of floats ranging between 0-1.
+ """
+ # Calculate the "hillshade" intensity.
+ intensity = self.hillshade(elevation, vert_exag, dx, dy, fraction)
+ intensity = intensity[..., np.newaxis]
+
+ # Blend the hillshade and rgb data using the specified mode
+ lookup = {
+ 'hsv': self.blend_hsv,
+ 'soft': self.blend_soft_light,
+ 'overlay': self.blend_overlay,
+ }
+ if blend_mode in lookup:
+ blend = lookup[blend_mode](rgb, intensity, **kwargs)
+ else:
+ try:
+ blend = blend_mode(rgb, intensity, **kwargs)
+ except TypeError as err:
+ raise ValueError('"blend_mode" must be callable or one of {}'
+ .format(lookup.keys)) from err
+
+ # Only apply result where hillshade intensity isn't masked
+ if np.ma.is_masked(intensity):
+ mask = intensity.mask[..., 0]
+ for i in range(3):
+ blend[..., i][mask] = rgb[..., i][mask]
+
+ return blend
+
+ def blend_hsv(self, rgb, intensity, hsv_max_sat=None, hsv_max_val=None,
+ hsv_min_val=None, hsv_min_sat=None):
+ """
+ Take the input data array, convert to HSV values in the given colormap,
+ then adjust those color values to give the impression of a shaded
+ relief map with a specified light source. RGBA values are returned,
+ which can then be used to plot the shaded image with imshow.
+
+ The color of the resulting image will be darkened by moving the (s, v)
+ values (in HSV colorspace) toward (hsv_min_sat, hsv_min_val) in the
+ shaded regions, or lightened by sliding (s, v) toward (hsv_max_sat,
+ hsv_max_val) in regions that are illuminated. The default extremes are
+ chose so that completely shaded points are nearly black (s = 1, v = 0)
+ and completely illuminated points are nearly white (s = 0, v = 1).
+
+ Parameters
+ ----------
+ rgb : `~numpy.ndarray`
+ An MxNx3 RGB array of floats ranging from 0 to 1 (color image).
+ intensity : `~numpy.ndarray`
+ An MxNx1 array of floats ranging from 0 to 1 (grayscale image).
+ hsv_max_sat : number, default: 1
+ The maximum saturation value that the *intensity* map can shift the
+ output image to.
+ hsv_min_sat : number, optional
+ The minimum saturation value that the *intensity* map can shift the
+ output image to. Defaults to 0.
+ hsv_max_val : number, optional
+ The maximum value ("v" in "hsv") that the *intensity* map can shift
+ the output image to. Defaults to 1.
+ hsv_min_val : number, optional
+ The minimum value ("v" in "hsv") that the *intensity* map can shift
+ the output image to. Defaults to 0.
+
+ Returns
+ -------
+ `~numpy.ndarray`
+ An MxNx3 RGB array representing the combined images.
+ """
+ # Backward compatibility...
+ if hsv_max_sat is None:
+ hsv_max_sat = self.hsv_max_sat
+ if hsv_max_val is None:
+ hsv_max_val = self.hsv_max_val
+ if hsv_min_sat is None:
+ hsv_min_sat = self.hsv_min_sat
+ if hsv_min_val is None:
+ hsv_min_val = self.hsv_min_val
+
+ # Expects a 2D intensity array scaled between -1 to 1...
+ intensity = intensity[..., 0]
+ intensity = 2 * intensity - 1
+
+ # Convert to rgb, then rgb to hsv
+ hsv = rgb_to_hsv(rgb[:, :, 0:3])
+ hue, sat, val = np.moveaxis(hsv, -1, 0)
+
+ # Modify hsv values (in place) to simulate illumination.
+ # putmask(A, mask, B) <=> A[mask] = B[mask]
+ np.putmask(sat, (np.abs(sat) > 1.e-10) & (intensity > 0),
+ (1 - intensity) * sat + intensity * hsv_max_sat)
+ np.putmask(sat, (np.abs(sat) > 1.e-10) & (intensity < 0),
+ (1 + intensity) * sat - intensity * hsv_min_sat)
+ np.putmask(val, intensity > 0,
+ (1 - intensity) * val + intensity * hsv_max_val)
+ np.putmask(val, intensity < 0,
+ (1 + intensity) * val - intensity * hsv_min_val)
+ np.clip(hsv[:, :, 1:], 0, 1, out=hsv[:, :, 1:])
+
+ # Convert modified hsv back to rgb.
+ return hsv_to_rgb(hsv)
+
+ def blend_soft_light(self, rgb, intensity):
+ """
+ Combine an RGB image with an intensity map using "soft light" blending,
+ using the "pegtop" formula.
+
+ Parameters
+ ----------
+ rgb : `~numpy.ndarray`
+ An MxNx3 RGB array of floats ranging from 0 to 1 (color image).
+ intensity : `~numpy.ndarray`
+ An MxNx1 array of floats ranging from 0 to 1 (grayscale image).
+
+ Returns
+ -------
+ `~numpy.ndarray`
+ An MxNx3 RGB array representing the combined images.
+ """
+ return 2 * intensity * rgb + (1 - 2 * intensity) * rgb**2
+
+ def blend_overlay(self, rgb, intensity):
+ """
+ Combine an RGB image with an intensity map using "overlay" blending.
+
+ Parameters
+ ----------
+ rgb : `~numpy.ndarray`
+ An MxNx3 RGB array of floats ranging from 0 to 1 (color image).
+ intensity : `~numpy.ndarray`
+ An MxNx1 array of floats ranging from 0 to 1 (grayscale image).
+
+ Returns
+ -------
+ ndarray
+ An MxNx3 RGB array representing the combined images.
+ """
+ low = 2 * intensity * rgb
+ high = 1 - 2 * (1 - intensity) * (1 - rgb)
+ return np.where(rgb <= 0.5, low, high)
+
+
+def from_levels_and_colors(levels, colors, extend='neither'):
+ """
+ A helper routine to generate a cmap and a norm instance which
+ behave similar to contourf's levels and colors arguments.
+
+ Parameters
+ ----------
+ levels : sequence of numbers
+ The quantization levels used to construct the `BoundaryNorm`.
+ Value ``v`` is quantized to level ``i`` if ``lev[i] <= v < lev[i+1]``.
+ colors : sequence of colors
+ The fill color to use for each level. If *extend* is "neither" there
+ must be ``n_level - 1`` colors. For an *extend* of "min" or "max" add
+ one extra color, and for an *extend* of "both" add two colors.
+ extend : {'neither', 'min', 'max', 'both'}, optional
+ The behaviour when a value falls out of range of the given levels.
+ See `~.Axes.contourf` for details.
+
+ Returns
+ -------
+ cmap : `~matplotlib.colors.Normalize`
+ norm : `~matplotlib.colors.Colormap`
+ """
+ slice_map = {
+ 'both': slice(1, -1),
+ 'min': slice(1, None),
+ 'max': slice(0, -1),
+ 'neither': slice(0, None),
+ }
+ _api.check_in_list(slice_map, extend=extend)
+ color_slice = slice_map[extend]
+
+ n_data_colors = len(levels) - 1
+ n_expected = n_data_colors + color_slice.start - (color_slice.stop or 0)
+ if len(colors) != n_expected:
+ raise ValueError(
+ f'With extend == {extend!r} and {len(levels)} levels, '
+ f'expected {n_expected} colors, but got {len(colors)}')
+
+ cmap = ListedColormap(colors[color_slice], N=n_data_colors)
+
+ if extend in ['min', 'both']:
+ cmap.set_under(colors[0])
+ else:
+ cmap.set_under('none')
+
+ if extend in ['max', 'both']:
+ cmap.set_over(colors[-1])
+ else:
+ cmap.set_over('none')
+
+ cmap.colorbar_extend = extend
+
+ norm = BoundaryNorm(levels, ncolors=n_data_colors)
+ return cmap, norm
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/container.py b/omnilmm/lib/python3.10/site-packages/matplotlib/container.py
new file mode 100644
index 0000000000000000000000000000000000000000..a58e55ca196cee6ac1a365c08a0b4f61317a0509
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/container.py
@@ -0,0 +1,142 @@
+from matplotlib import cbook
+from matplotlib.artist import Artist
+
+
+class Container(tuple):
+ """
+ Base class for containers.
+
+ Containers are classes that collect semantically related Artists such as
+ the bars of a bar plot.
+ """
+
+ def __repr__(self):
+ return ("<{} object of {} artists>"
+ .format(type(self).__name__, len(self)))
+
+ def __new__(cls, *args, **kwargs):
+ return tuple.__new__(cls, args[0])
+
+ def __init__(self, kl, label=None):
+ self._callbacks = cbook.CallbackRegistry(signals=["pchanged"])
+ self._remove_method = None
+ self.set_label(label)
+
+ def remove(self):
+ for c in cbook.flatten(
+ self, scalarp=lambda x: isinstance(x, Artist)):
+ if c is not None:
+ c.remove()
+ if self._remove_method:
+ self._remove_method(self)
+
+ def get_children(self):
+ return [child for child in cbook.flatten(self) if child is not None]
+
+ get_label = Artist.get_label
+ set_label = Artist.set_label
+ add_callback = Artist.add_callback
+ remove_callback = Artist.remove_callback
+ pchanged = Artist.pchanged
+
+
+class BarContainer(Container):
+ """
+ Container for the artists of bar plots (e.g. created by `.Axes.bar`).
+
+ The container can be treated as a tuple of the *patches* themselves.
+ Additionally, you can access these and further parameters by the
+ attributes.
+
+ Attributes
+ ----------
+ patches : list of :class:`~matplotlib.patches.Rectangle`
+ The artists of the bars.
+
+ errorbar : None or :class:`~matplotlib.container.ErrorbarContainer`
+ A container for the error bar artists if error bars are present.
+ *None* otherwise.
+
+ datavalues : None or array-like
+ The underlying data values corresponding to the bars.
+
+ orientation : {'vertical', 'horizontal'}, default: None
+ If 'vertical', the bars are assumed to be vertical.
+ If 'horizontal', the bars are assumed to be horizontal.
+
+ """
+
+ def __init__(self, patches, errorbar=None, *, datavalues=None,
+ orientation=None, **kwargs):
+ self.patches = patches
+ self.errorbar = errorbar
+ self.datavalues = datavalues
+ self.orientation = orientation
+ super().__init__(patches, **kwargs)
+
+
+class ErrorbarContainer(Container):
+ """
+ Container for the artists of error bars (e.g. created by `.Axes.errorbar`).
+
+ The container can be treated as the *lines* tuple itself.
+ Additionally, you can access these and further parameters by the
+ attributes.
+
+ Attributes
+ ----------
+ lines : tuple
+ Tuple of ``(data_line, caplines, barlinecols)``.
+
+ - data_line : :class:`~matplotlib.lines.Line2D` instance of
+ x, y plot markers and/or line.
+ - caplines : tuple of :class:`~matplotlib.lines.Line2D` instances of
+ the error bar caps.
+ - barlinecols : list of :class:`~matplotlib.collections.LineCollection`
+ with the horizontal and vertical error ranges.
+
+ has_xerr, has_yerr : bool
+ ``True`` if the errorbar has x/y errors.
+
+ """
+
+ def __init__(self, lines, has_xerr=False, has_yerr=False, **kwargs):
+ self.lines = lines
+ self.has_xerr = has_xerr
+ self.has_yerr = has_yerr
+ super().__init__(lines, **kwargs)
+
+
+class StemContainer(Container):
+ """
+ Container for the artists created in a :meth:`.Axes.stem` plot.
+
+ The container can be treated like a namedtuple ``(markerline, stemlines,
+ baseline)``.
+
+ Attributes
+ ----------
+ markerline : :class:`~matplotlib.lines.Line2D`
+ The artist of the markers at the stem heads.
+
+ stemlines : list of :class:`~matplotlib.lines.Line2D`
+ The artists of the vertical lines for all stems.
+
+ baseline : :class:`~matplotlib.lines.Line2D`
+ The artist of the horizontal baseline.
+ """
+ def __init__(self, markerline_stemlines_baseline, **kwargs):
+ """
+ Parameters
+ ----------
+ markerline_stemlines_baseline : tuple
+ Tuple of ``(markerline, stemlines, baseline)``.
+ ``markerline`` contains the `.LineCollection` of the markers,
+ ``stemlines`` is a `.LineCollection` of the main lines,
+ ``baseline`` is the `.Line2D` of the baseline.
+ """
+ markerline, stemlines, baseline = markerline_stemlines_baseline
+ self.markerline = markerline
+ self.stemlines = stemlines
+ self.baseline = baseline
+ super().__init__(markerline_stemlines_baseline, **kwargs)
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/contour.py b/omnilmm/lib/python3.10/site-packages/matplotlib/contour.py
new file mode 100644
index 0000000000000000000000000000000000000000..ecb2547c8bf1ce390d869026181fddadcbcf36cd
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/contour.py
@@ -0,0 +1,1783 @@
+"""
+Classes to support contour plotting and labelling for the Axes class.
+"""
+
+import functools
+from numbers import Integral
+
+import numpy as np
+from numpy import ma
+
+import matplotlib as mpl
+from matplotlib import _api, _docstring
+from matplotlib.backend_bases import MouseButton
+from matplotlib.text import Text
+import matplotlib.path as mpath
+import matplotlib.ticker as ticker
+import matplotlib.cm as cm
+import matplotlib.colors as mcolors
+import matplotlib.collections as mcoll
+import matplotlib.font_manager as font_manager
+import matplotlib.cbook as cbook
+import matplotlib.patches as mpatches
+import matplotlib.transforms as mtransforms
+
+
+# We can't use a single line collection for contour because a line
+# collection can have only a single line style, and we want to be able to have
+# dashed negative contours, for example, and solid positive contours.
+# We could use a single polygon collection for filled contours, but it
+# seems better to keep line and filled contours similar, with one collection
+# per level.
+
+
+@_api.deprecated("3.7", alternative="Text.set_transform_rotates_text")
+class ClabelText(Text):
+ """
+ Unlike the ordinary text, the get_rotation returns an updated
+ angle in the pixel coordinate assuming that the input rotation is
+ an angle in data coordinate (or whatever transform set).
+ """
+
+ def get_rotation(self):
+ new_angle, = self.get_transform().transform_angles(
+ [super().get_rotation()], [self.get_position()])
+ return new_angle
+
+
+def _contour_labeler_event_handler(cs, inline, inline_spacing, event):
+ canvas = cs.axes.figure.canvas
+ is_button = event.name == "button_press_event"
+ is_key = event.name == "key_press_event"
+ # Quit (even if not in infinite mode; this is consistent with
+ # MATLAB and sometimes quite useful, but will require the user to
+ # test how many points were actually returned before using data).
+ if (is_button and event.button == MouseButton.MIDDLE
+ or is_key and event.key in ["escape", "enter"]):
+ canvas.stop_event_loop()
+ # Pop last click.
+ elif (is_button and event.button == MouseButton.RIGHT
+ or is_key and event.key in ["backspace", "delete"]):
+ # Unfortunately, if one is doing inline labels, then there is currently
+ # no way to fix the broken contour - once humpty-dumpty is broken, he
+ # can't be put back together. In inline mode, this does nothing.
+ if not inline:
+ cs.pop_label()
+ canvas.draw()
+ # Add new click.
+ elif (is_button and event.button == MouseButton.LEFT
+ # On macOS/gtk, some keys return None.
+ or is_key and event.key is not None):
+ if event.inaxes == cs.axes:
+ cs.add_label_near(event.x, event.y, transform=False,
+ inline=inline, inline_spacing=inline_spacing)
+ canvas.draw()
+
+
+class ContourLabeler:
+ """Mixin to provide labelling capability to `.ContourSet`."""
+
+ def clabel(self, levels=None, *,
+ fontsize=None, inline=True, inline_spacing=5, fmt=None,
+ colors=None, use_clabeltext=False, manual=False,
+ rightside_up=True, zorder=None):
+ """
+ Label a contour plot.
+
+ Adds labels to line contours in this `.ContourSet` (which inherits from
+ this mixin class).
+
+ Parameters
+ ----------
+ levels : array-like, optional
+ A list of level values, that should be labeled. The list must be
+ a subset of ``cs.levels``. If not given, all levels are labeled.
+
+ fontsize : str or float, default: :rc:`font.size`
+ Size in points or relative size e.g., 'smaller', 'x-large'.
+ See `.Text.set_size` for accepted string values.
+
+ colors : color or colors or None, default: None
+ The label colors:
+
+ - If *None*, the color of each label matches the color of
+ the corresponding contour.
+
+ - If one string color, e.g., *colors* = 'r' or *colors* =
+ 'red', all labels will be plotted in this color.
+
+ - If a tuple of colors (string, float, rgb, etc), different labels
+ will be plotted in different colors in the order specified.
+
+ inline : bool, default: True
+ If ``True`` the underlying contour is removed where the label is
+ placed.
+
+ inline_spacing : float, default: 5
+ Space in pixels to leave on each side of label when placing inline.
+
+ This spacing will be exact for labels at locations where the
+ contour is straight, less so for labels on curved contours.
+
+ fmt : `.Formatter` or str or callable or dict, optional
+ How the levels are formatted:
+
+ - If a `.Formatter`, it is used to format all levels at once, using
+ its `.Formatter.format_ticks` method.
+ - If a str, it is interpreted as a %-style format string.
+ - If a callable, it is called with one level at a time and should
+ return the corresponding label.
+ - If a dict, it should directly map levels to labels.
+
+ The default is to use a standard `.ScalarFormatter`.
+
+ manual : bool or iterable, default: False
+ If ``True``, contour labels will be placed manually using
+ mouse clicks. Click the first button near a contour to
+ add a label, click the second button (or potentially both
+ mouse buttons at once) to finish adding labels. The third
+ button can be used to remove the last label added, but
+ only if labels are not inline. Alternatively, the keyboard
+ can be used to select label locations (enter to end label
+ placement, delete or backspace act like the third mouse button,
+ and any other key will select a label location).
+
+ *manual* can also be an iterable object of (x, y) tuples.
+ Contour labels will be created as if mouse is clicked at each
+ (x, y) position.
+
+ rightside_up : bool, default: True
+ If ``True``, label rotations will always be plus
+ or minus 90 degrees from level.
+
+ use_clabeltext : bool, default: False
+ If ``True``, use `.Text.set_transform_rotates_text` to ensure that
+ label rotation is updated whenever the axes aspect changes.
+
+ zorder : float or None, default: ``(2 + contour.get_zorder())``
+ zorder of the contour labels.
+
+ Returns
+ -------
+ labels
+ A list of `.Text` instances for the labels.
+ """
+
+ # clabel basically takes the input arguments and uses them to
+ # add a list of "label specific" attributes to the ContourSet
+ # object. These attributes are all of the form label* and names
+ # should be fairly self explanatory.
+ #
+ # Once these attributes are set, clabel passes control to the
+ # labels method (case of automatic label placement) or
+ # `BlockingContourLabeler` (case of manual label placement).
+
+ if fmt is None:
+ fmt = ticker.ScalarFormatter(useOffset=False)
+ fmt.create_dummy_axis()
+ self.labelFmt = fmt
+ self._use_clabeltext = use_clabeltext
+ # Detect if manual selection is desired and remove from argument list.
+ self.labelManual = manual
+ self.rightside_up = rightside_up
+ if zorder is None:
+ self._clabel_zorder = 2+self._contour_zorder
+ else:
+ self._clabel_zorder = zorder
+
+ if levels is None:
+ levels = self.levels
+ indices = list(range(len(self.cvalues)))
+ else:
+ levlabs = list(levels)
+ indices, levels = [], []
+ for i, lev in enumerate(self.levels):
+ if lev in levlabs:
+ indices.append(i)
+ levels.append(lev)
+ if len(levels) < len(levlabs):
+ raise ValueError(f"Specified levels {levlabs} don't match "
+ f"available levels {self.levels}")
+ self.labelLevelList = levels
+ self.labelIndiceList = indices
+
+ self._label_font_props = font_manager.FontProperties(size=fontsize)
+
+ if colors is None:
+ self.labelMappable = self
+ self.labelCValueList = np.take(self.cvalues, self.labelIndiceList)
+ else:
+ cmap = mcolors.ListedColormap(colors, N=len(self.labelLevelList))
+ self.labelCValueList = list(range(len(self.labelLevelList)))
+ self.labelMappable = cm.ScalarMappable(cmap=cmap,
+ norm=mcolors.NoNorm())
+
+ self.labelXYs = []
+
+ if np.iterable(manual):
+ for x, y in manual:
+ self.add_label_near(x, y, inline, inline_spacing)
+ elif manual:
+ print('Select label locations manually using first mouse button.')
+ print('End manual selection with second mouse button.')
+ if not inline:
+ print('Remove last label by clicking third mouse button.')
+ mpl._blocking_input.blocking_input_loop(
+ self.axes.figure, ["button_press_event", "key_press_event"],
+ timeout=-1, handler=functools.partial(
+ _contour_labeler_event_handler,
+ self, inline, inline_spacing))
+ else:
+ self.labels(inline, inline_spacing)
+
+ return cbook.silent_list('text.Text', self.labelTexts)
+
+ @_api.deprecated("3.7", alternative="cs.labelTexts[0].get_font()")
+ @property
+ def labelFontProps(self):
+ return self._label_font_props
+
+ @_api.deprecated("3.7", alternative=(
+ "[cs.labelTexts[0].get_font().get_size()] * len(cs.labelLevelList)"))
+ @property
+ def labelFontSizeList(self):
+ return [self._label_font_props.get_size()] * len(self.labelLevelList)
+
+ @_api.deprecated("3.7", alternative="cs.labelTexts")
+ @property
+ def labelTextsList(self):
+ return cbook.silent_list('text.Text', self.labelTexts)
+
+ def print_label(self, linecontour, labelwidth):
+ """Return whether a contour is long enough to hold a label."""
+ return (len(linecontour) > 10 * labelwidth
+ or (np.ptp(linecontour, axis=0) > 1.2 * labelwidth).any())
+
+ def too_close(self, x, y, lw):
+ """Return whether a label is already near this location."""
+ thresh = (1.2 * lw) ** 2
+ return any((x - loc[0]) ** 2 + (y - loc[1]) ** 2 < thresh
+ for loc in self.labelXYs)
+
+ def _get_nth_label_width(self, nth):
+ """Return the width of the *nth* label, in pixels."""
+ fig = self.axes.figure
+ renderer = fig._get_renderer()
+ return (Text(0, 0,
+ self.get_text(self.labelLevelList[nth], self.labelFmt),
+ figure=fig, fontproperties=self._label_font_props)
+ .get_window_extent(renderer).width)
+
+ @_api.deprecated("3.7", alternative="Artist.set")
+ def set_label_props(self, label, text, color):
+ """Set the label properties - color, fontsize, text."""
+ label.set_text(text)
+ label.set_color(color)
+ label.set_fontproperties(self._label_font_props)
+ label.set_clip_box(self.axes.bbox)
+
+ def get_text(self, lev, fmt):
+ """Get the text of the label."""
+ if isinstance(lev, str):
+ return lev
+ elif isinstance(fmt, dict):
+ return fmt.get(lev, '%1.3f')
+ elif callable(getattr(fmt, "format_ticks", None)):
+ return fmt.format_ticks([*self.labelLevelList, lev])[-1]
+ elif callable(fmt):
+ return fmt(lev)
+ else:
+ return fmt % lev
+
+ def locate_label(self, linecontour, labelwidth):
+ """
+ Find good place to draw a label (relatively flat part of the contour).
+ """
+ ctr_size = len(linecontour)
+ n_blocks = int(np.ceil(ctr_size / labelwidth)) if labelwidth > 1 else 1
+ block_size = ctr_size if n_blocks == 1 else int(labelwidth)
+ # Split contour into blocks of length ``block_size``, filling the last
+ # block by cycling the contour start (per `np.resize` semantics). (Due
+ # to cycling, the index returned is taken modulo ctr_size.)
+ xx = np.resize(linecontour[:, 0], (n_blocks, block_size))
+ yy = np.resize(linecontour[:, 1], (n_blocks, block_size))
+ yfirst = yy[:, :1]
+ ylast = yy[:, -1:]
+ xfirst = xx[:, :1]
+ xlast = xx[:, -1:]
+ s = (yfirst - yy) * (xlast - xfirst) - (xfirst - xx) * (ylast - yfirst)
+ l = np.hypot(xlast - xfirst, ylast - yfirst)
+ # Ignore warning that divide by zero throws, as this is a valid option
+ with np.errstate(divide='ignore', invalid='ignore'):
+ distances = (abs(s) / l).sum(axis=-1)
+ # Labels are drawn in the middle of the block (``hbsize``) where the
+ # contour is the closest (per ``distances``) to a straight line, but
+ # not `too_close()` to a preexisting label.
+ hbsize = block_size // 2
+ adist = np.argsort(distances)
+ # If all candidates are `too_close()`, go back to the straightest part
+ # (``adist[0]``).
+ for idx in np.append(adist, adist[0]):
+ x, y = xx[idx, hbsize], yy[idx, hbsize]
+ if not self.too_close(x, y, labelwidth):
+ break
+ return x, y, (idx * block_size + hbsize) % ctr_size
+
+ def calc_label_rot_and_inline(self, slc, ind, lw, lc=None, spacing=5):
+ """
+ Calculate the appropriate label rotation given the linecontour
+ coordinates in screen units, the index of the label location and the
+ label width.
+
+ If *lc* is not None or empty, also break contours and compute
+ inlining.
+
+ *spacing* is the empty space to leave around the label, in pixels.
+
+ Both tasks are done together to avoid calculating path lengths
+ multiple times, which is relatively costly.
+
+ The method used here involves computing the path length along the
+ contour in pixel coordinates and then looking approximately (label
+ width / 2) away from central point to determine rotation and then to
+ break contour if desired.
+ """
+
+ if lc is None:
+ lc = []
+ # Half the label width
+ hlw = lw / 2.0
+
+ # Check if closed and, if so, rotate contour so label is at edge
+ closed = _is_closed_polygon(slc)
+ if closed:
+ slc = np.concatenate([slc[ind:-1], slc[:ind + 1]])
+ if len(lc): # Rotate lc also if not empty
+ lc = np.concatenate([lc[ind:-1], lc[:ind + 1]])
+ ind = 0
+
+ # Calculate path lengths
+ pl = np.zeros(slc.shape[0], dtype=float)
+ dx = np.diff(slc, axis=0)
+ pl[1:] = np.cumsum(np.hypot(dx[:, 0], dx[:, 1]))
+ pl = pl - pl[ind]
+
+ # Use linear interpolation to get points around label
+ xi = np.array([-hlw, hlw])
+ if closed: # Look at end also for closed contours
+ dp = np.array([pl[-1], 0])
+ else:
+ dp = np.zeros_like(xi)
+
+ # Get angle of vector between the two ends of the label - must be
+ # calculated in pixel space for text rotation to work correctly.
+ (dx,), (dy,) = (np.diff(np.interp(dp + xi, pl, slc_col))
+ for slc_col in slc.T)
+ rotation = np.rad2deg(np.arctan2(dy, dx))
+
+ if self.rightside_up:
+ # Fix angle so text is never upside-down
+ rotation = (rotation + 90) % 180 - 90
+
+ # Break contour if desired
+ nlc = []
+ if len(lc):
+ # Expand range by spacing
+ xi = dp + xi + np.array([-spacing, spacing])
+
+ # Get (integer) indices near points of interest; use -1 as marker
+ # for out of bounds.
+ I = np.interp(xi, pl, np.arange(len(pl)), left=-1, right=-1)
+ I = [np.floor(I[0]).astype(int), np.ceil(I[1]).astype(int)]
+ if I[0] != -1:
+ xy1 = [np.interp(xi[0], pl, lc_col) for lc_col in lc.T]
+ if I[1] != -1:
+ xy2 = [np.interp(xi[1], pl, lc_col) for lc_col in lc.T]
+
+ # Actually break contours
+ if closed:
+ # This will remove contour if shorter than label
+ if all(i != -1 for i in I):
+ nlc.append(np.row_stack([xy2, lc[I[1]:I[0]+1], xy1]))
+ else:
+ # These will remove pieces of contour if they have length zero
+ if I[0] != -1:
+ nlc.append(np.row_stack([lc[:I[0]+1], xy1]))
+ if I[1] != -1:
+ nlc.append(np.row_stack([xy2, lc[I[1]:]]))
+
+ # The current implementation removes contours completely
+ # covered by labels. Uncomment line below to keep
+ # original contour if this is the preferred behavior.
+ # if not len(nlc): nlc = [ lc ]
+
+ return rotation, nlc
+
+ def add_label(self, x, y, rotation, lev, cvalue):
+ """Add contour label without `.Text.set_transform_rotates_text`."""
+ data_x, data_y = self.axes.transData.inverted().transform((x, y))
+ t = Text(
+ data_x, data_y,
+ text=self.get_text(lev, self.labelFmt),
+ rotation=rotation,
+ horizontalalignment='center', verticalalignment='center',
+ zorder=self._clabel_zorder,
+ color=self.labelMappable.to_rgba(cvalue, alpha=self.alpha),
+ fontproperties=self._label_font_props,
+ clip_box=self.axes.bbox)
+ self.labelTexts.append(t)
+ self.labelCValues.append(cvalue)
+ self.labelXYs.append((x, y))
+ # Add label to plot here - useful for manual mode label selection
+ self.axes.add_artist(t)
+
+ def add_label_clabeltext(self, x, y, rotation, lev, cvalue):
+ """Add contour label with `.Text.set_transform_rotates_text`."""
+ self.add_label(x, y, rotation, lev, cvalue)
+ # Grab the last added text, and reconfigure its rotation.
+ t = self.labelTexts[-1]
+ data_rotation, = self.axes.transData.inverted().transform_angles(
+ [rotation], [[x, y]])
+ t.set(rotation=data_rotation, transform_rotates_text=True)
+
+ def add_label_near(self, x, y, inline=True, inline_spacing=5,
+ transform=None):
+ """
+ Add a label near the point ``(x, y)``.
+
+ Parameters
+ ----------
+ x, y : float
+ The approximate location of the label.
+ inline : bool, default: True
+ If *True* remove the segment of the contour beneath the label.
+ inline_spacing : int, default: 5
+ Space in pixels to leave on each side of label when placing
+ inline. This spacing will be exact for labels at locations where
+ the contour is straight, less so for labels on curved contours.
+ transform : `.Transform` or `False`, default: ``self.axes.transData``
+ A transform applied to ``(x, y)`` before labeling. The default
+ causes ``(x, y)`` to be interpreted as data coordinates. `False`
+ is a synonym for `.IdentityTransform`; i.e. ``(x, y)`` should be
+ interpreted as display coordinates.
+ """
+
+ if transform is None:
+ transform = self.axes.transData
+ if transform:
+ x, y = transform.transform((x, y))
+
+ # find the nearest contour _in screen units_
+ conmin, segmin, imin, xmin, ymin = self.find_nearest_contour(
+ x, y, self.labelIndiceList)[:5]
+
+ # calc_label_rot_and_inline() requires that (xmin, ymin)
+ # be a vertex in the path. So, if it isn't, add a vertex here
+ paths = self.collections[conmin].get_paths() # paths of correct coll.
+ lc = paths[segmin].vertices # vertices of correct segment
+ # Where should the new vertex be added in data-units?
+ xcmin = self.axes.transData.inverted().transform([xmin, ymin])
+ if not np.allclose(xcmin, lc[imin]):
+ # No vertex is close enough, so add a new point in the vertices and
+ # replace the path by the new one.
+ lc = np.insert(lc, imin, xcmin, axis=0)
+ paths[segmin] = mpath.Path(lc)
+
+ # Get index of nearest level in subset of levels used for labeling
+ lmin = self.labelIndiceList.index(conmin)
+
+ # Get label width for rotating labels and breaking contours
+ lw = self._get_nth_label_width(lmin)
+
+ # Figure out label rotation.
+ rotation, nlc = self.calc_label_rot_and_inline(
+ self.axes.transData.transform(lc), # to pixel space.
+ imin, lw, lc if inline else None, inline_spacing)
+
+ self.add_label(xmin, ymin, rotation, self.labelLevelList[lmin],
+ self.labelCValueList[lmin])
+
+ if inline:
+ # Remove old, not looping over paths so we can do this up front
+ paths.pop(segmin)
+
+ # Add paths if not empty or single point
+ paths.extend([mpath.Path(n) for n in nlc if len(n) > 1])
+
+ def pop_label(self, index=-1):
+ """Defaults to removing last label, but any index can be supplied"""
+ self.labelCValues.pop(index)
+ t = self.labelTexts.pop(index)
+ t.remove()
+
+ def labels(self, inline, inline_spacing):
+
+ if self._use_clabeltext:
+ add_label = self.add_label_clabeltext
+ else:
+ add_label = self.add_label
+
+ for idx, (icon, lev, cvalue) in enumerate(zip(
+ self.labelIndiceList,
+ self.labelLevelList,
+ self.labelCValueList,
+ )):
+
+ con = self.collections[icon]
+ trans = con.get_transform()
+ lw = self._get_nth_label_width(idx)
+ additions = []
+ paths = con.get_paths()
+ for segNum, linepath in enumerate(paths):
+ lc = linepath.vertices # Line contour
+ slc = trans.transform(lc) # Line contour in screen coords
+
+ # Check if long enough for a label
+ if self.print_label(slc, lw):
+ x, y, ind = self.locate_label(slc, lw)
+
+ rotation, new = self.calc_label_rot_and_inline(
+ slc, ind, lw, lc if inline else None, inline_spacing)
+
+ # Actually add the label
+ add_label(x, y, rotation, lev, cvalue)
+
+ # If inline, add new contours
+ if inline:
+ for n in new:
+ # Add path if not empty or single point
+ if len(n) > 1:
+ additions.append(mpath.Path(n))
+ else: # If not adding label, keep old path
+ additions.append(linepath)
+
+ # After looping over all segments on a contour, replace old paths
+ # by new ones if inlining.
+ if inline:
+ paths[:] = additions
+
+ def remove(self):
+ for text in self.labelTexts:
+ text.remove()
+
+
+def _is_closed_polygon(X):
+ """
+ Return whether first and last object in a sequence are the same. These are
+ presumably coordinates on a polygonal curve, in which case this function
+ tests if that curve is closed.
+ """
+ return np.allclose(X[0], X[-1], rtol=1e-10, atol=1e-13)
+
+
+def _find_closest_point_on_path(xys, p):
+ """
+ Parameters
+ ----------
+ xys : (N, 2) array-like
+ Coordinates of vertices.
+ p : (float, float)
+ Coordinates of point.
+
+ Returns
+ -------
+ d2min : float
+ Minimum square distance of *p* to *xys*.
+ proj : (float, float)
+ Projection of *p* onto *xys*.
+ imin : (int, int)
+ Consecutive indices of vertices of segment in *xys* where *proj* is.
+ Segments are considered as including their end-points; i.e. if the
+ closest point on the path is a node in *xys* with index *i*, this
+ returns ``(i-1, i)``. For the special case where *xys* is a single
+ point, this returns ``(0, 0)``.
+ """
+ if len(xys) == 1:
+ return (((p - xys[0]) ** 2).sum(), xys[0], (0, 0))
+ dxys = xys[1:] - xys[:-1] # Individual segment vectors.
+ norms = (dxys ** 2).sum(axis=1)
+ norms[norms == 0] = 1 # For zero-length segment, replace 0/0 by 0/1.
+ rel_projs = np.clip( # Project onto each segment in relative 0-1 coords.
+ ((p - xys[:-1]) * dxys).sum(axis=1) / norms,
+ 0, 1)[:, None]
+ projs = xys[:-1] + rel_projs * dxys # Projs. onto each segment, in (x, y).
+ d2s = ((projs - p) ** 2).sum(axis=1) # Squared distances.
+ imin = np.argmin(d2s)
+ return (d2s[imin], projs[imin], (imin, imin+1))
+
+
+_docstring.interpd.update(contour_set_attributes=r"""
+Attributes
+----------
+ax : `~matplotlib.axes.Axes`
+ The Axes object in which the contours are drawn.
+
+collections : `.silent_list` of `.PathCollection`\s
+ The `.Artist`\s representing the contour. This is a list of
+ `.PathCollection`\s for both line and filled contours.
+
+levels : array
+ The values of the contour levels.
+
+layers : array
+ Same as levels for line contours; half-way between
+ levels for filled contours. See ``ContourSet._process_colors``.
+""")
+
+
+@_docstring.dedent_interpd
+class ContourSet(cm.ScalarMappable, ContourLabeler):
+ """
+ Store a set of contour lines or filled regions.
+
+ User-callable method: `~.Axes.clabel`
+
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+
+ levels : [level0, level1, ..., leveln]
+ A list of floating point numbers indicating the contour levels.
+
+ allsegs : [level0segs, level1segs, ...]
+ List of all the polygon segments for all the *levels*.
+ For contour lines ``len(allsegs) == len(levels)``, and for
+ filled contour regions ``len(allsegs) = len(levels)-1``. The lists
+ should look like ::
+
+ level0segs = [polygon0, polygon1, ...]
+ polygon0 = [[x0, y0], [x1, y1], ...]
+
+ allkinds : ``None`` or [level0kinds, level1kinds, ...]
+ Optional list of all the polygon vertex kinds (code types), as
+ described and used in Path. This is used to allow multiply-
+ connected paths such as holes within filled polygons.
+ If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
+ should look like ::
+
+ level0kinds = [polygon0kinds, ...]
+ polygon0kinds = [vertexcode0, vertexcode1, ...]
+
+ If *allkinds* is not ``None``, usually all polygons for a
+ particular contour level are grouped together so that
+ ``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.
+
+ **kwargs
+ Keyword arguments are as described in the docstring of
+ `~.Axes.contour`.
+
+ %(contour_set_attributes)s
+ """
+
+ def __init__(self, ax, *args,
+ levels=None, filled=False, linewidths=None, linestyles=None,
+ hatches=(None,), alpha=None, origin=None, extent=None,
+ cmap=None, colors=None, norm=None, vmin=None, vmax=None,
+ extend='neither', antialiased=None, nchunk=0, locator=None,
+ transform=None, negative_linestyles=None,
+ **kwargs):
+ """
+ Draw contour lines or filled regions, depending on
+ whether keyword arg *filled* is ``False`` (default) or ``True``.
+
+ Call signature::
+
+ ContourSet(ax, levels, allsegs, [allkinds], **kwargs)
+
+ Parameters
+ ----------
+ ax : `~matplotlib.axes.Axes`
+ The `~.axes.Axes` object to draw on.
+
+ levels : [level0, level1, ..., leveln]
+ A list of floating point numbers indicating the contour
+ levels.
+
+ allsegs : [level0segs, level1segs, ...]
+ List of all the polygon segments for all the *levels*.
+ For contour lines ``len(allsegs) == len(levels)``, and for
+ filled contour regions ``len(allsegs) = len(levels)-1``. The lists
+ should look like ::
+
+ level0segs = [polygon0, polygon1, ...]
+ polygon0 = [[x0, y0], [x1, y1], ...]
+
+ allkinds : [level0kinds, level1kinds, ...], optional
+ Optional list of all the polygon vertex kinds (code types), as
+ described and used in Path. This is used to allow multiply-
+ connected paths such as holes within filled polygons.
+ If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
+ should look like ::
+
+ level0kinds = [polygon0kinds, ...]
+ polygon0kinds = [vertexcode0, vertexcode1, ...]
+
+ If *allkinds* is not ``None``, usually all polygons for a
+ particular contour level are grouped together so that
+ ``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.
+
+ **kwargs
+ Keyword arguments are as described in the docstring of
+ `~.Axes.contour`.
+ """
+ self.axes = ax
+ self.levels = levels
+ self.filled = filled
+ self.linewidths = linewidths
+ self.linestyles = linestyles
+ self.hatches = hatches
+ self.alpha = alpha
+ self.origin = origin
+ self.extent = extent
+ self.colors = colors
+ self.extend = extend
+ self.antialiased = antialiased
+ if self.antialiased is None and self.filled:
+ # Eliminate artifacts; we are not stroking the boundaries.
+ self.antialiased = False
+ # The default for line contours will be taken from the
+ # LineCollection default, which uses :rc:`lines.antialiased`.
+
+ self.nchunk = nchunk
+ self.locator = locator
+ if (isinstance(norm, mcolors.LogNorm)
+ or isinstance(self.locator, ticker.LogLocator)):
+ self.logscale = True
+ if norm is None:
+ norm = mcolors.LogNorm()
+ else:
+ self.logscale = False
+
+ _api.check_in_list([None, 'lower', 'upper', 'image'], origin=origin)
+ if self.extent is not None and len(self.extent) != 4:
+ raise ValueError(
+ "If given, 'extent' must be None or (x0, x1, y0, y1)")
+ if self.colors is not None and cmap is not None:
+ raise ValueError('Either colors or cmap must be None')
+ if self.origin == 'image':
+ self.origin = mpl.rcParams['image.origin']
+
+ self._transform = transform
+
+ 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']
+
+ kwargs = self._process_args(*args, **kwargs)
+ self._process_levels()
+
+ self._extend_min = self.extend in ['min', 'both']
+ self._extend_max = self.extend in ['max', 'both']
+ if self.colors is not None:
+ ncolors = len(self.levels)
+ if self.filled:
+ ncolors -= 1
+ i0 = 0
+
+ # Handle the case where colors are given for the extended
+ # parts of the contour.
+
+ use_set_under_over = False
+ # if we are extending the lower end, and we've been given enough
+ # colors then skip the first color in the resulting cmap. For the
+ # extend_max case we don't need to worry about passing more colors
+ # than ncolors as ListedColormap will clip.
+ total_levels = (ncolors +
+ int(self._extend_min) +
+ int(self._extend_max))
+ if (len(self.colors) == total_levels and
+ (self._extend_min or self._extend_max)):
+ use_set_under_over = True
+ if self._extend_min:
+ i0 = 1
+
+ cmap = mcolors.ListedColormap(self.colors[i0:None], N=ncolors)
+
+ if use_set_under_over:
+ if self._extend_min:
+ cmap.set_under(self.colors[0])
+ if self._extend_max:
+ cmap.set_over(self.colors[-1])
+
+ self.collections = cbook.silent_list(None)
+
+ # label lists must be initialized here
+ self.labelTexts = []
+ self.labelCValues = []
+
+ kw = {'cmap': cmap}
+ if norm is not None:
+ kw['norm'] = norm
+ # sets self.cmap, norm if needed;
+ cm.ScalarMappable.__init__(self, **kw)
+ if vmin is not None:
+ self.norm.vmin = vmin
+ if vmax is not None:
+ self.norm.vmax = vmax
+ self._process_colors()
+
+ if getattr(self, 'allsegs', None) is None:
+ self.allsegs, self.allkinds = self._get_allsegs_and_allkinds()
+ elif self.allkinds is None:
+ # allsegs specified in constructor may or may not have allkinds as
+ # well. Must ensure allkinds can be zipped below.
+ self.allkinds = [None] * len(self.allsegs)
+
+ if self.filled:
+ if self.linewidths is not None:
+ _api.warn_external('linewidths is ignored by contourf')
+ # Lower and upper contour levels.
+ lowers, uppers = self._get_lowers_and_uppers()
+ # Default zorder taken from Collection
+ self._contour_zorder = kwargs.pop('zorder', 1)
+
+ self.collections[:] = [
+ mcoll.PathCollection(
+ self._make_paths(segs, kinds),
+ antialiaseds=(self.antialiased,),
+ edgecolors='none',
+ alpha=self.alpha,
+ transform=self.get_transform(),
+ zorder=self._contour_zorder)
+ for level, level_upper, segs, kinds
+ in zip(lowers, uppers, self.allsegs, self.allkinds)]
+ else:
+ self.tlinewidths = tlinewidths = self._process_linewidths()
+ tlinestyles = self._process_linestyles()
+ aa = self.antialiased
+ if aa is not None:
+ aa = (self.antialiased,)
+ # Default zorder taken from LineCollection, which is higher than
+ # for filled contours so that lines are displayed on top.
+ self._contour_zorder = kwargs.pop('zorder', 2)
+
+ self.collections[:] = [
+ mcoll.PathCollection(
+ self._make_paths(segs, kinds),
+ facecolors="none",
+ antialiaseds=aa,
+ linewidths=width,
+ linestyles=[lstyle],
+ alpha=self.alpha,
+ transform=self.get_transform(),
+ zorder=self._contour_zorder,
+ label='_nolegend_')
+ for level, width, lstyle, segs, kinds
+ in zip(self.levels, tlinewidths, tlinestyles, self.allsegs,
+ self.allkinds)]
+
+ for col in self.collections:
+ self.axes.add_collection(col, autolim=False)
+ col.sticky_edges.x[:] = [self._mins[0], self._maxs[0]]
+ col.sticky_edges.y[:] = [self._mins[1], self._maxs[1]]
+ self.axes.update_datalim([self._mins, self._maxs])
+ self.axes.autoscale_view(tight=True)
+
+ self.changed() # set the colors
+
+ if kwargs:
+ _api.warn_external(
+ 'The following kwargs were not used by contour: ' +
+ ", ".join(map(repr, kwargs))
+ )
+
+ def get_transform(self):
+ """Return the `.Transform` instance used by this ContourSet."""
+ if self._transform is None:
+ self._transform = self.axes.transData
+ elif (not isinstance(self._transform, mtransforms.Transform)
+ and hasattr(self._transform, '_as_mpl_transform')):
+ self._transform = self._transform._as_mpl_transform(self.axes)
+ return self._transform
+
+ def __getstate__(self):
+ state = self.__dict__.copy()
+ # the C object _contour_generator cannot currently be pickled. This
+ # isn't a big issue as it is not actually used once the contour has
+ # been calculated.
+ state['_contour_generator'] = None
+ return state
+
+ def legend_elements(self, variable_name='x', str_format=str):
+ """
+ Return a list of artists and labels suitable for passing through
+ to `~.Axes.legend` which represent this ContourSet.
+
+ The labels have the form "0 < x <= 1" stating the data ranges which
+ the artists represent.
+
+ Parameters
+ ----------
+ variable_name : str
+ The string used inside the inequality used on the labels.
+ str_format : function: float -> str
+ Function used to format the numbers in the labels.
+
+ Returns
+ -------
+ artists : list[`.Artist`]
+ A list of the artists.
+ labels : list[str]
+ A list of the labels.
+ """
+ artists = []
+ labels = []
+
+ if self.filled:
+ lowers, uppers = self._get_lowers_and_uppers()
+ n_levels = len(self.collections)
+
+ for i, (collection, lower, upper) in enumerate(
+ zip(self.collections, lowers, uppers)):
+ patch = mpatches.Rectangle(
+ (0, 0), 1, 1,
+ facecolor=collection.get_facecolor()[0],
+ hatch=collection.get_hatch(),
+ alpha=collection.get_alpha())
+ artists.append(patch)
+
+ lower = str_format(lower)
+ upper = str_format(upper)
+
+ if i == 0 and self.extend in ('min', 'both'):
+ labels.append(fr'${variable_name} \leq {lower}s$')
+ elif i == n_levels - 1 and self.extend in ('max', 'both'):
+ labels.append(fr'${variable_name} > {upper}s$')
+ else:
+ labels.append(fr'${lower} < {variable_name} \leq {upper}$')
+ else:
+ for collection, level in zip(self.collections, self.levels):
+
+ patch = mcoll.LineCollection(None)
+ patch.update_from(collection)
+
+ artists.append(patch)
+ # format the level for insertion into the labels
+ level = str_format(level)
+ labels.append(fr'${variable_name} = {level}$')
+
+ return artists, labels
+
+ def _process_args(self, *args, **kwargs):
+ """
+ Process *args* and *kwargs*; override in derived classes.
+
+ Must set self.levels, self.zmin and self.zmax, and update axes limits.
+ """
+ self.levels = args[0]
+ self.allsegs = args[1]
+ self.allkinds = args[2] if len(args) > 2 else None
+ self.zmax = np.max(self.levels)
+ self.zmin = np.min(self.levels)
+
+ # Check lengths of levels and allsegs.
+ if self.filled:
+ if len(self.allsegs) != len(self.levels) - 1:
+ raise ValueError('must be one less number of segments as '
+ 'levels')
+ else:
+ if len(self.allsegs) != len(self.levels):
+ raise ValueError('must be same number of segments as levels')
+
+ # Check length of allkinds.
+ if (self.allkinds is not None and
+ len(self.allkinds) != len(self.allsegs)):
+ raise ValueError('allkinds has different length to allsegs')
+
+ # Determine x, y bounds and update axes data limits.
+ flatseglist = [s for seg in self.allsegs for s in seg]
+ points = np.concatenate(flatseglist, axis=0)
+ self._mins = points.min(axis=0)
+ self._maxs = points.max(axis=0)
+
+ return kwargs
+
+ def _get_allsegs_and_allkinds(self):
+ """Compute ``allsegs`` and ``allkinds`` using C extension."""
+ allsegs = []
+ allkinds = []
+ if self.filled:
+ lowers, uppers = self._get_lowers_and_uppers()
+ for level, level_upper in zip(lowers, uppers):
+ vertices, kinds = \
+ self._contour_generator.create_filled_contour(
+ level, level_upper)
+ allsegs.append(vertices)
+ allkinds.append(kinds)
+ else:
+ for level in self.levels:
+ vertices, kinds = self._contour_generator.create_contour(level)
+ allsegs.append(vertices)
+ allkinds.append(kinds)
+ return allsegs, allkinds
+
+ def _get_lowers_and_uppers(self):
+ """
+ Return ``(lowers, uppers)`` for filled contours.
+ """
+ lowers = self._levels[:-1]
+ if self.zmin == lowers[0]:
+ # Include minimum values in lowest interval
+ lowers = lowers.copy() # so we don't change self._levels
+ if self.logscale:
+ lowers[0] = 0.99 * self.zmin
+ else:
+ lowers[0] -= 1
+ uppers = self._levels[1:]
+ return (lowers, uppers)
+
+ def _make_paths(self, segs, kinds):
+ """
+ Create and return Path objects for the specified segments and optional
+ kind codes. *segs* is a list of numpy arrays, each array is either a
+ closed line loop or open line strip of 2D points with a shape of
+ (npoints, 2). *kinds* is either None or a list (with the same length
+ as *segs*) of numpy arrays, each array is of shape (npoints,) and
+ contains the kind codes for the corresponding line in *segs*. If
+ *kinds* is None then the Path constructor creates the kind codes
+ assuming that the line is an open strip.
+ """
+ if kinds is None:
+ return [mpath.Path(seg) for seg in segs]
+ else:
+ return [mpath.Path(seg, codes=kind) for seg, kind
+ in zip(segs, kinds)]
+
+ def changed(self):
+ if not hasattr(self, "cvalues"):
+ # Just return after calling the super() changed function
+ cm.ScalarMappable.changed(self)
+ return
+ # Force an autoscale immediately because self.to_rgba() calls
+ # autoscale_None() internally with the data passed to it,
+ # so if vmin/vmax are not set yet, this would override them with
+ # content from *cvalues* rather than levels like we want
+ self.norm.autoscale_None(self.levels)
+ tcolors = [(tuple(rgba),)
+ for rgba in self.to_rgba(self.cvalues, alpha=self.alpha)]
+ self.tcolors = tcolors
+ hatches = self.hatches * len(tcolors)
+ for color, hatch, collection in zip(tcolors, hatches,
+ self.collections):
+ if self.filled:
+ collection.set_facecolor(color)
+ # update the collection's hatch (may be None)
+ collection.set_hatch(hatch)
+ else:
+ collection.set_edgecolor(color)
+ for label, cv in zip(self.labelTexts, self.labelCValues):
+ label.set_alpha(self.alpha)
+ label.set_color(self.labelMappable.to_rgba(cv))
+ # add label colors
+ cm.ScalarMappable.changed(self)
+
+ def _autolev(self, N):
+ """
+ Select contour levels to span the data.
+
+ The target number of levels, *N*, is used only when the
+ scale is not log and default locator is used.
+
+ We need two more levels for filled contours than for
+ line contours, because for the latter we need to specify
+ the lower and upper boundary of each range. For example,
+ a single contour boundary, say at z = 0, requires only
+ one contour line, but two filled regions, and therefore
+ three levels to provide boundaries for both regions.
+ """
+ if self.locator is None:
+ if self.logscale:
+ self.locator = ticker.LogLocator()
+ else:
+ self.locator = ticker.MaxNLocator(N + 1, min_n_ticks=1)
+
+ lev = self.locator.tick_values(self.zmin, self.zmax)
+
+ try:
+ if self.locator._symmetric:
+ return lev
+ except AttributeError:
+ pass
+
+ # Trim excess levels the locator may have supplied.
+ under = np.nonzero(lev < self.zmin)[0]
+ i0 = under[-1] if len(under) else 0
+ over = np.nonzero(lev > self.zmax)[0]
+ i1 = over[0] + 1 if len(over) else len(lev)
+ if self.extend in ('min', 'both'):
+ i0 += 1
+ if self.extend in ('max', 'both'):
+ i1 -= 1
+
+ if i1 - i0 < 3:
+ i0, i1 = 0, len(lev)
+
+ return lev[i0:i1]
+
+ def _process_contour_level_args(self, args, z_dtype):
+ """
+ Determine the contour levels and store in self.levels.
+ """
+ if self.levels is None:
+ if args:
+ levels_arg = args[0]
+ elif np.issubdtype(z_dtype, bool):
+ if self.filled:
+ levels_arg = [0, .5, 1]
+ else:
+ levels_arg = [.5]
+ else:
+ levels_arg = 7 # Default, hard-wired.
+ else:
+ levels_arg = self.levels
+ if isinstance(levels_arg, Integral):
+ self.levels = self._autolev(levels_arg)
+ else:
+ self.levels = np.asarray(levels_arg, np.float64)
+ if self.filled and len(self.levels) < 2:
+ raise ValueError("Filled contours require at least 2 levels.")
+ if len(self.levels) > 1 and np.min(np.diff(self.levels)) <= 0.0:
+ raise ValueError("Contour levels must be increasing")
+
+ def _process_levels(self):
+ """
+ Assign values to :attr:`layers` based on :attr:`levels`,
+ adding extended layers as needed if contours are filled.
+
+ For line contours, layers simply coincide with levels;
+ a line is a thin layer. No extended levels are needed
+ with line contours.
+ """
+ # Make a private _levels to include extended regions; we
+ # want to leave the original levels attribute unchanged.
+ # (Colorbar needs this even for line contours.)
+ self._levels = list(self.levels)
+
+ if self.logscale:
+ lower, upper = 1e-250, 1e250
+ else:
+ lower, upper = -1e250, 1e250
+
+ if self.extend in ('both', 'min'):
+ self._levels.insert(0, lower)
+ if self.extend in ('both', 'max'):
+ self._levels.append(upper)
+ self._levels = np.asarray(self._levels)
+
+ if not self.filled:
+ self.layers = self.levels
+ return
+
+ # Layer values are mid-way between levels in screen space.
+ if self.logscale:
+ # Avoid overflow by taking sqrt before multiplying.
+ self.layers = (np.sqrt(self._levels[:-1])
+ * np.sqrt(self._levels[1:]))
+ else:
+ self.layers = 0.5 * (self._levels[:-1] + self._levels[1:])
+
+ def _process_colors(self):
+ """
+ Color argument processing for contouring.
+
+ Note that we base the colormapping on the contour levels
+ and layers, not on the actual range of the Z values. This
+ means we don't have to worry about bad values in Z, and we
+ always have the full dynamic range available for the selected
+ levels.
+
+ The color is based on the midpoint of the layer, except for
+ extended end layers. By default, the norm vmin and vmax
+ are the extreme values of the non-extended levels. Hence,
+ the layer color extremes are not the extreme values of
+ the colormap itself, but approach those values as the number
+ of levels increases. An advantage of this scheme is that
+ line contours, when added to filled contours, take on
+ colors that are consistent with those of the filled regions;
+ for example, a contour line on the boundary between two
+ regions will have a color intermediate between those
+ of the regions.
+
+ """
+ self.monochrome = self.cmap.monochrome
+ if self.colors is not None:
+ # Generate integers for direct indexing.
+ i0, i1 = 0, len(self.levels)
+ if self.filled:
+ i1 -= 1
+ # Out of range indices for over and under:
+ if self.extend in ('both', 'min'):
+ i0 -= 1
+ if self.extend in ('both', 'max'):
+ i1 += 1
+ self.cvalues = list(range(i0, i1))
+ self.set_norm(mcolors.NoNorm())
+ else:
+ self.cvalues = self.layers
+ self.set_array(self.levels)
+ self.autoscale_None()
+ if self.extend in ('both', 'max', 'min'):
+ self.norm.clip = False
+
+ # self.tcolors are set by the "changed" method
+
+ def _process_linewidths(self):
+ linewidths = self.linewidths
+ Nlev = len(self.levels)
+ if linewidths is None:
+ default_linewidth = mpl.rcParams['contour.linewidth']
+ if default_linewidth is None:
+ default_linewidth = mpl.rcParams['lines.linewidth']
+ tlinewidths = [(default_linewidth,)] * Nlev
+ else:
+ if not np.iterable(linewidths):
+ linewidths = [linewidths] * Nlev
+ else:
+ linewidths = list(linewidths)
+ if len(linewidths) < Nlev:
+ nreps = int(np.ceil(Nlev / len(linewidths)))
+ linewidths = linewidths * nreps
+ if len(linewidths) > Nlev:
+ linewidths = linewidths[:Nlev]
+ tlinewidths = [(w,) for w in linewidths]
+ return tlinewidths
+
+ def _process_linestyles(self):
+ linestyles = self.linestyles
+ Nlev = len(self.levels)
+ if linestyles is None:
+ tlinestyles = ['solid'] * Nlev
+ if self.monochrome:
+ eps = - (self.zmax - self.zmin) * 1e-15
+ for i, lev in enumerate(self.levels):
+ if lev < eps:
+ tlinestyles[i] = self.negative_linestyles
+ else:
+ if isinstance(linestyles, str):
+ tlinestyles = [linestyles] * Nlev
+ elif np.iterable(linestyles):
+ tlinestyles = list(linestyles)
+ if len(tlinestyles) < Nlev:
+ nreps = int(np.ceil(Nlev / len(linestyles)))
+ tlinestyles = tlinestyles * nreps
+ if len(tlinestyles) > Nlev:
+ tlinestyles = tlinestyles[:Nlev]
+ else:
+ raise ValueError("Unrecognized type for linestyles kwarg")
+ return tlinestyles
+
+ def get_alpha(self):
+ """Return alpha to be applied to all ContourSet artists."""
+ return self.alpha
+
+ def set_alpha(self, alpha):
+ """
+ Set the alpha blending value for all ContourSet artists.
+ *alpha* must be between 0 (transparent) and 1 (opaque).
+ """
+ self.alpha = alpha
+ self.changed()
+
+ def find_nearest_contour(self, x, y, indices=None, pixel=True):
+ """
+ Find the point in the contour plot that is closest to ``(x, y)``.
+
+ This method does not support filled contours.
+
+ Parameters
+ ----------
+ x, y : float
+ The reference point.
+ indices : list of int or None, default: None
+ Indices of contour levels to consider. If None (the default), all
+ levels are considered.
+ pixel : bool, default: True
+ If *True*, measure distance in pixel (screen) space, which is
+ useful for manual contour labeling; else, measure distance in axes
+ space.
+
+ Returns
+ -------
+ contour : `.Collection`
+ The contour that is closest to ``(x, y)``.
+ segment : int
+ The index of the `.Path` in *contour* that is closest to
+ ``(x, y)``.
+ index : int
+ The index of the path segment in *segment* that is closest to
+ ``(x, y)``.
+ xmin, ymin : float
+ The point in the contour plot that is closest to ``(x, y)``.
+ d2 : float
+ The squared distance from ``(xmin, ymin)`` to ``(x, y)``.
+ """
+
+ # This function uses a method that is probably quite
+ # inefficient based on converting each contour segment to
+ # pixel coordinates and then comparing the given point to
+ # those coordinates for each contour. This will probably be
+ # quite slow for complex contours, but for normal use it works
+ # sufficiently well that the time is not noticeable.
+ # Nonetheless, improvements could probably be made.
+
+ if self.filled:
+ raise ValueError("Method does not support filled contours.")
+
+ if indices is None:
+ indices = range(len(self.collections))
+
+ d2min = np.inf
+ conmin = None
+ segmin = None
+ imin = None
+ xmin = None
+ ymin = None
+
+ point = np.array([x, y])
+
+ for icon in indices:
+ con = self.collections[icon]
+ trans = con.get_transform()
+ paths = con.get_paths()
+
+ for segNum, linepath in enumerate(paths):
+ lc = linepath.vertices
+ # transfer all data points to screen coordinates if desired
+ if pixel:
+ lc = trans.transform(lc)
+
+ d2, xc, leg = _find_closest_point_on_path(lc, point)
+ if d2 < d2min:
+ d2min = d2
+ conmin = icon
+ segmin = segNum
+ imin = leg[1]
+ xmin = xc[0]
+ ymin = xc[1]
+
+ return (conmin, segmin, imin, xmin, ymin, d2min)
+
+ def remove(self):
+ super().remove()
+ for coll in self.collections:
+ coll.remove()
+
+
+@_docstring.dedent_interpd
+class QuadContourSet(ContourSet):
+ """
+ Create and store a set of contour lines or filled regions.
+
+ This class is typically not instantiated directly by the user but by
+ `~.Axes.contour` and `~.Axes.contourf`.
+
+ %(contour_set_attributes)s
+ """
+
+ def _process_args(self, *args, corner_mask=None, algorithm=None, **kwargs):
+ """
+ Process args and kwargs.
+ """
+ if isinstance(args[0], QuadContourSet):
+ if self.levels is None:
+ self.levels = args[0].levels
+ self.zmin = args[0].zmin
+ self.zmax = args[0].zmax
+ self._corner_mask = args[0]._corner_mask
+ contour_generator = args[0]._contour_generator
+ self._mins = args[0]._mins
+ self._maxs = args[0]._maxs
+ self._algorithm = args[0]._algorithm
+ else:
+ import contourpy
+
+ if algorithm is None:
+ algorithm = mpl.rcParams['contour.algorithm']
+ mpl.rcParams.validate["contour.algorithm"](algorithm)
+ self._algorithm = algorithm
+
+ if corner_mask is None:
+ if self._algorithm == "mpl2005":
+ # mpl2005 does not support corner_mask=True so if not
+ # specifically requested then disable it.
+ corner_mask = False
+ else:
+ corner_mask = mpl.rcParams['contour.corner_mask']
+ self._corner_mask = corner_mask
+
+ x, y, z = self._contour_args(args, kwargs)
+
+ contour_generator = contourpy.contour_generator(
+ x, y, z, name=self._algorithm, corner_mask=self._corner_mask,
+ line_type=contourpy.LineType.SeparateCode,
+ fill_type=contourpy.FillType.OuterCode,
+ chunk_size=self.nchunk)
+
+ t = self.get_transform()
+
+ # if the transform is not trans data, and some part of it
+ # contains transData, transform the xs and ys to data coordinates
+ if (t != self.axes.transData and
+ any(t.contains_branch_seperately(self.axes.transData))):
+ trans_to_data = t - self.axes.transData
+ pts = np.vstack([x.flat, y.flat]).T
+ transformed_pts = trans_to_data.transform(pts)
+ x = transformed_pts[..., 0]
+ y = transformed_pts[..., 1]
+
+ self._mins = [ma.min(x), ma.min(y)]
+ self._maxs = [ma.max(x), ma.max(y)]
+
+ self._contour_generator = contour_generator
+
+ return kwargs
+
+ def _contour_args(self, args, kwargs):
+ if self.filled:
+ fn = 'contourf'
+ else:
+ fn = 'contour'
+ nargs = len(args)
+ if nargs <= 2:
+ z, *args = args
+ z = ma.asarray(z)
+ x, y = self._initialize_x_y(z)
+ elif nargs <= 4:
+ x, y, z_orig, *args = args
+ x, y, z = self._check_xyz(x, y, z_orig, kwargs)
+ else:
+ raise _api.nargs_error(fn, takes="from 1 to 4", given=nargs)
+ z = ma.masked_invalid(z, copy=False)
+ self.zmax = float(z.max())
+ self.zmin = float(z.min())
+ if self.logscale and self.zmin <= 0:
+ z = ma.masked_where(z <= 0, z)
+ _api.warn_external('Log scale: values of z <= 0 have been masked')
+ self.zmin = float(z.min())
+ self._process_contour_level_args(args, z.dtype)
+ return (x, y, z)
+
+ def _check_xyz(self, x, y, z, kwargs):
+ """
+ Check that the shapes of the input arrays match; if x and y are 1D,
+ convert them to 2D using meshgrid.
+ """
+ x, y = self.axes._process_unit_info([("x", x), ("y", y)], kwargs)
+
+ x = np.asarray(x, dtype=np.float64)
+ y = np.asarray(y, dtype=np.float64)
+ z = ma.asarray(z)
+
+ if z.ndim != 2:
+ raise TypeError(f"Input z must be 2D, not {z.ndim}D")
+ if z.shape[0] < 2 or z.shape[1] < 2:
+ raise TypeError(f"Input z must be at least a (2, 2) shaped array, "
+ f"but has shape {z.shape}")
+ Ny, Nx = z.shape
+
+ if x.ndim != y.ndim:
+ raise TypeError(f"Number of dimensions of x ({x.ndim}) and y "
+ f"({y.ndim}) do not match")
+ if x.ndim == 1:
+ nx, = x.shape
+ ny, = y.shape
+ if nx != Nx:
+ raise TypeError(f"Length of x ({nx}) must match number of "
+ f"columns in z ({Nx})")
+ if ny != Ny:
+ raise TypeError(f"Length of y ({ny}) must match number of "
+ f"rows in z ({Ny})")
+ x, y = np.meshgrid(x, y)
+ elif x.ndim == 2:
+ if x.shape != z.shape:
+ raise TypeError(
+ f"Shapes of x {x.shape} and z {z.shape} do not match")
+ if y.shape != z.shape:
+ raise TypeError(
+ f"Shapes of y {y.shape} and z {z.shape} do not match")
+ else:
+ raise TypeError(f"Inputs x and y must be 1D or 2D, not {x.ndim}D")
+
+ return x, y, z
+
+ def _initialize_x_y(self, z):
+ """
+ Return X, Y arrays such that contour(Z) will match imshow(Z)
+ if origin is not None.
+ The center of pixel Z[i, j] depends on origin:
+ if origin is None, x = j, y = i;
+ if origin is 'lower', x = j + 0.5, y = i + 0.5;
+ if origin is 'upper', x = j + 0.5, y = Nrows - i - 0.5
+ If extent is not None, x and y will be scaled to match,
+ as in imshow.
+ If origin is None and extent is not None, then extent
+ will give the minimum and maximum values of x and y.
+ """
+ if z.ndim != 2:
+ raise TypeError(f"Input z must be 2D, not {z.ndim}D")
+ elif z.shape[0] < 2 or z.shape[1] < 2:
+ raise TypeError(f"Input z must be at least a (2, 2) shaped array, "
+ f"but has shape {z.shape}")
+ else:
+ Ny, Nx = z.shape
+ if self.origin is None: # Not for image-matching.
+ if self.extent is None:
+ return np.meshgrid(np.arange(Nx), np.arange(Ny))
+ else:
+ x0, x1, y0, y1 = self.extent
+ x = np.linspace(x0, x1, Nx)
+ y = np.linspace(y0, y1, Ny)
+ return np.meshgrid(x, y)
+ # Match image behavior:
+ if self.extent is None:
+ x0, x1, y0, y1 = (0, Nx, 0, Ny)
+ else:
+ x0, x1, y0, y1 = self.extent
+ dx = (x1 - x0) / Nx
+ dy = (y1 - y0) / Ny
+ x = x0 + (np.arange(Nx) + 0.5) * dx
+ y = y0 + (np.arange(Ny) + 0.5) * dy
+ if self.origin == 'upper':
+ y = y[::-1]
+ return np.meshgrid(x, y)
+
+
+_docstring.interpd.update(contour_doc="""
+`.contour` and `.contourf` draw contour lines and filled contours,
+respectively. Except as noted, function signatures and return values
+are the same for both versions.
+
+Parameters
+----------
+X, Y : array-like, optional
+ The coordinates of the values in *Z*.
+
+ *X* and *Y* must both be 2D with the same shape as *Z* (e.g.
+ created via `numpy.meshgrid`), or they must both be 1-D such
+ that ``len(X) == N`` is the number of columns in *Z* and
+ ``len(Y) == M`` is the number of rows in *Z*.
+
+ *X* and *Y* must both be ordered monotonically.
+
+ If not given, they are assumed to be integer indices, i.e.
+ ``X = range(N)``, ``Y = range(M)``.
+
+Z : (M, N) array-like
+ The height values over which the contour is drawn. Color-mapping is
+ controlled by *cmap*, *norm*, *vmin*, and *vmax*.
+
+levels : int or array-like, optional
+ Determines the number and positions of the contour lines / regions.
+
+ If an int *n*, use `~matplotlib.ticker.MaxNLocator`, which tries
+ to automatically choose no more than *n+1* "nice" contour levels
+ between minimum and maximum numeric values of *Z*.
+
+ If array-like, draw contour lines at the specified levels.
+ The values must be in increasing order.
+
+Returns
+-------
+`~.contour.QuadContourSet`
+
+Other Parameters
+----------------
+corner_mask : bool, default: :rc:`contour.corner_mask`
+ Enable/disable corner masking, which only has an effect if *Z* is
+ a masked array. If ``False``, any quad touching a masked point is
+ masked out. If ``True``, only the triangular corners of quads
+ nearest those points are always masked out, other triangular
+ corners comprising three unmasked points are contoured as usual.
+
+colors : color string or sequence of colors, optional
+ The colors of the levels, i.e. the lines for `.contour` and the
+ areas for `.contourf`.
+
+ The sequence is cycled for the levels in ascending order. If the
+ sequence is shorter than the number of levels, it's repeated.
+
+ As a shortcut, single color strings may be used in place of
+ one-element lists, i.e. ``'red'`` instead of ``['red']`` to color
+ all levels with the same color. This shortcut does only work for
+ color strings, not for other ways of specifying colors.
+
+ By default (value *None*), the colormap specified by *cmap*
+ will be used.
+
+alpha : float, default: 1
+ The alpha blending value, between 0 (transparent) and 1 (opaque).
+
+%(cmap_doc)s
+
+ This parameter is ignored if *colors* is set.
+
+%(norm_doc)s
+
+ This parameter is ignored if *colors* is set.
+
+%(vmin_vmax_doc)s
+
+ If *vmin* or *vmax* are not given, the default color scaling is based on
+ *levels*.
+
+ This parameter is ignored if *colors* is set.
+
+origin : {*None*, 'upper', 'lower', 'image'}, default: None
+ Determines the orientation and exact position of *Z* by specifying
+ the position of ``Z[0, 0]``. This is only relevant, if *X*, *Y*
+ are not given.
+
+ - *None*: ``Z[0, 0]`` is at X=0, Y=0 in the lower left corner.
+ - 'lower': ``Z[0, 0]`` is at X=0.5, Y=0.5 in the lower left corner.
+ - 'upper': ``Z[0, 0]`` is at X=N+0.5, Y=0.5 in the upper left
+ corner.
+ - 'image': Use the value from :rc:`image.origin`.
+
+extent : (x0, x1, y0, y1), optional
+ If *origin* is not *None*, then *extent* is interpreted as in
+ `.imshow`: it gives the outer pixel boundaries. In this case, the
+ position of Z[0, 0] is the center of the pixel, not a corner. If
+ *origin* is *None*, then (*x0*, *y0*) is the position of Z[0, 0],
+ and (*x1*, *y1*) is the position of Z[-1, -1].
+
+ This argument is ignored if *X* and *Y* are specified in the call
+ to contour.
+
+locator : ticker.Locator subclass, optional
+ The locator is used to determine the contour levels if they
+ are not given explicitly via *levels*.
+ Defaults to `~.ticker.MaxNLocator`.
+
+extend : {'neither', 'both', 'min', 'max'}, default: 'neither'
+ Determines the ``contourf``-coloring of values that are outside the
+ *levels* range.
+
+ If 'neither', values outside the *levels* range are not colored.
+ If 'min', 'max' or 'both', color the values below, above or below
+ and above the *levels* range.
+
+ Values below ``min(levels)`` and above ``max(levels)`` are mapped
+ to the under/over values of the `.Colormap`. Note that most
+ colormaps do not have dedicated colors for these by default, so
+ that the over and under values are the edge values of the colormap.
+ You may want to set these values explicitly using
+ `.Colormap.set_under` and `.Colormap.set_over`.
+
+ .. note::
+
+ An existing `.QuadContourSet` does not get notified if
+ properties of its colormap are changed. Therefore, an explicit
+ call `.QuadContourSet.changed()` is needed after modifying the
+ colormap. The explicit call can be left out, if a colorbar is
+ assigned to the `.QuadContourSet` because it internally calls
+ `.QuadContourSet.changed()`.
+
+ Example::
+
+ x = np.arange(1, 10)
+ y = x.reshape(-1, 1)
+ h = x * y
+
+ cs = plt.contourf(h, levels=[10, 30, 50],
+ colors=['#808080', '#A0A0A0', '#C0C0C0'], extend='both')
+ cs.cmap.set_over('red')
+ cs.cmap.set_under('blue')
+ cs.changed()
+
+xunits, yunits : registered units, optional
+ Override axis units by specifying an instance of a
+ :class:`matplotlib.units.ConversionInterface`.
+
+antialiased : bool, optional
+ Enable antialiasing, overriding the defaults. For
+ filled contours, the default is *False*. For line contours,
+ it is taken from :rc:`lines.antialiased`.
+
+nchunk : int >= 0, optional
+ If 0, no subdivision of the domain. Specify a positive integer to
+ divide the domain into subdomains of *nchunk* by *nchunk* quads.
+ Chunking reduces the maximum length of polygons generated by the
+ contouring algorithm which reduces the rendering workload passed
+ on to the backend and also requires slightly less RAM. It can
+ however introduce rendering artifacts at chunk boundaries depending
+ on the backend, the *antialiased* flag and value of *alpha*.
+
+linewidths : float or array-like, default: :rc:`contour.linewidth`
+ *Only applies to* `.contour`.
+
+ The line width of the contour lines.
+
+ If a number, all levels will be plotted with this linewidth.
+
+ If a sequence, the levels in ascending order will be plotted with
+ the linewidths in the order specified.
+
+ If None, this falls back to :rc:`lines.linewidth`.
+
+linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, optional
+ *Only applies to* `.contour`.
+
+ If *linestyles* is *None*, the default is 'solid' unless the lines are
+ monochrome. In that case, negative contours will instead take their
+ linestyle from the *negative_linestyles* argument.
+
+ *linestyles* can also be an iterable of the above strings specifying a set
+ of linestyles to be used. If this iterable is shorter than the number of
+ contour levels it will be repeated as necessary.
+
+negative_linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, \
+ optional
+ *Only applies to* `.contour`.
+
+ If *linestyles* is *None* and the lines are monochrome, this argument
+ specifies the line style for negative contours.
+
+ If *negative_linestyles* is *None*, the default is taken from
+ :rc:`contour.negative_linestyles`.
+
+ *negative_linestyles* can also be an iterable of the above strings
+ specifying a set of linestyles to be used. If this iterable is shorter than
+ the number of contour levels it will be repeated as necessary.
+
+hatches : list[str], optional
+ *Only applies to* `.contourf`.
+
+ A list of cross hatch patterns to use on the filled areas.
+ If None, no hatching will be added to the contour.
+ Hatching is supported in the PostScript, PDF, SVG and Agg
+ backends only.
+
+algorithm : {'mpl2005', 'mpl2014', 'serial', 'threaded'}, optional
+ Which contouring algorithm to use to calculate the contour lines and
+ polygons. The algorithms are implemented in
+ `ContourPy
`_, consult the
+ `ContourPy documentation `_ for
+ further information.
+
+ The default is taken from :rc:`contour.algorithm`.
+
+data : indexable object, optional
+ DATA_PARAMETER_PLACEHOLDER
+
+Notes
+-----
+1. `.contourf` differs from the MATLAB version in that it does not draw
+ the polygon edges. To draw edges, add line contours with calls to
+ `.contour`.
+
+2. `.contourf` fills intervals that are closed at the top; that is, for
+ boundaries *z1* and *z2*, the filled region is::
+
+ z1 < Z <= z2
+
+ except for the lowest interval, which is closed on both sides (i.e.
+ it includes the lowest value).
+
+3. `.contour` and `.contourf` use a `marching squares
+ `_ algorithm to
+ compute contour locations. More information can be found in
+ `ContourPy documentation `_.
+""" % _docstring.interpd.params)
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/dates.py b/omnilmm/lib/python3.10/site-packages/matplotlib/dates.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c2293e039860cf0402c01cd0299591b40eb07df
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/dates.py
@@ -0,0 +1,1942 @@
+"""
+Matplotlib provides sophisticated date plotting capabilities, standing on the
+shoulders of python :mod:`datetime` and the add-on module dateutil_.
+
+By default, Matplotlib uses the units machinery described in
+`~matplotlib.units` to convert `datetime.datetime`, and `numpy.datetime64`
+objects when plotted on an x- or y-axis. The user does not
+need to do anything for dates to be formatted, but dates often have strict
+formatting needs, so this module provides many axis locators and formatters.
+A basic example using `numpy.datetime64` is::
+
+ import numpy as np
+
+ times = np.arange(np.datetime64('2001-01-02'),
+ np.datetime64('2002-02-03'), np.timedelta64(75, 'm'))
+ y = np.random.randn(len(times))
+
+ fig, ax = plt.subplots()
+ ax.plot(times, y)
+
+.. seealso::
+
+ - :doc:`/gallery/text_labels_and_annotations/date`
+ - :doc:`/gallery/ticks/date_concise_formatter`
+ - :doc:`/gallery/ticks/date_demo_convert`
+
+.. _date-format:
+
+Matplotlib date format
+----------------------
+
+Matplotlib represents dates using floating point numbers specifying the number
+of days since a default epoch of 1970-01-01 UTC; for example,
+1970-01-01, 06:00 is the floating point number 0.25. The formatters and
+locators require the use of `datetime.datetime` objects, so only dates between
+year 0001 and 9999 can be represented. Microsecond precision
+is achievable for (approximately) 70 years on either side of the epoch, and
+20 microseconds for the rest of the allowable range of dates (year 0001 to
+9999). The epoch can be changed at import time via `.dates.set_epoch` or
+:rc:`dates.epoch` to other dates if necessary; see
+:doc:`/gallery/ticks/date_precision_and_epochs` for a discussion.
+
+.. note::
+
+ Before Matplotlib 3.3, the epoch was 0000-12-31 which lost modern
+ microsecond precision and also made the default axis limit of 0 an invalid
+ datetime. In 3.3 the epoch was changed as above. To convert old
+ ordinal floats to the new epoch, users can do::
+
+ new_ordinal = old_ordinal + mdates.date2num(np.datetime64('0000-12-31'))
+
+
+There are a number of helper functions to convert between :mod:`datetime`
+objects and Matplotlib dates:
+
+.. currentmodule:: matplotlib.dates
+
+.. autosummary::
+ :nosignatures:
+
+ datestr2num
+ date2num
+ num2date
+ num2timedelta
+ drange
+ set_epoch
+ get_epoch
+
+.. note::
+
+ Like Python's `datetime.datetime`, Matplotlib uses the Gregorian calendar
+ for all conversions between dates and floating point numbers. This practice
+ is not universal, and calendar differences can cause confusing
+ differences between what Python and Matplotlib give as the number of days
+ since 0001-01-01 and what other software and databases yield. For
+ example, the US Naval Observatory uses a calendar that switches
+ from Julian to Gregorian in October, 1582. Hence, using their
+ calculator, the number of days between 0001-01-01 and 2006-04-01 is
+ 732403, whereas using the Gregorian calendar via the datetime
+ module we find::
+
+ In [1]: date(2006, 4, 1).toordinal() - date(1, 1, 1).toordinal()
+ Out[1]: 732401
+
+All the Matplotlib date converters, tickers and formatters are timezone aware.
+If no explicit timezone is provided, :rc:`timezone` is assumed, provided as a
+string. If you want to use a different timezone, pass the *tz* keyword
+argument of `num2date` to any date tickers or locators you create. This can
+be either a `datetime.tzinfo` instance or a string with the timezone name that
+can be parsed by `~dateutil.tz.gettz`.
+
+A wide range of specific and general purpose date tick locators and
+formatters are provided in this module. See
+:mod:`matplotlib.ticker` for general information on tick locators
+and formatters. These are described below.
+
+The dateutil_ module provides additional code to handle date ticking, making it
+easy to place ticks on any kinds of dates. See examples below.
+
+.. _dateutil: https://dateutil.readthedocs.io
+
+Date tickers
+------------
+
+Most of the date tickers can locate single or multiple values. For example::
+
+ # import constants for the days of the week
+ from matplotlib.dates import MO, TU, WE, TH, FR, SA, SU
+
+ # tick on Mondays every week
+ loc = WeekdayLocator(byweekday=MO, tz=tz)
+
+ # tick on Mondays and Saturdays
+ loc = WeekdayLocator(byweekday=(MO, SA))
+
+In addition, most of the constructors take an interval argument::
+
+ # tick on Mondays every second week
+ loc = WeekdayLocator(byweekday=MO, interval=2)
+
+The rrule locator allows completely general date ticking::
+
+ # tick every 5th easter
+ rule = rrulewrapper(YEARLY, byeaster=1, interval=5)
+ loc = RRuleLocator(rule)
+
+The available date tickers are:
+
+* `MicrosecondLocator`: Locate microseconds.
+
+* `SecondLocator`: Locate seconds.
+
+* `MinuteLocator`: Locate minutes.
+
+* `HourLocator`: Locate hours.
+
+* `DayLocator`: Locate specified days of the month.
+
+* `WeekdayLocator`: Locate days of the week, e.g., MO, TU.
+
+* `MonthLocator`: Locate months, e.g., 7 for July.
+
+* `YearLocator`: Locate years that are multiples of base.
+
+* `RRuleLocator`: Locate using a `rrulewrapper`.
+ `rrulewrapper` is a simple wrapper around dateutil_'s `dateutil.rrule`
+ which allow almost arbitrary date tick specifications.
+ See :doc:`rrule example `.
+
+* `AutoDateLocator`: On autoscale, this class picks the best `DateLocator`
+ (e.g., `RRuleLocator`) to set the view limits and the tick locations. If
+ called with ``interval_multiples=True`` it will make ticks line up with
+ sensible multiples of the tick intervals. For example, if the interval is
+ 4 hours, it will pick hours 0, 4, 8, etc. as ticks. This behaviour is not
+ guaranteed by default.
+
+Date formatters
+---------------
+
+The available date formatters are:
+
+* `AutoDateFormatter`: attempts to figure out the best format to use. This is
+ most useful when used with the `AutoDateLocator`.
+
+* `ConciseDateFormatter`: also attempts to figure out the best format to use,
+ and to make the format as compact as possible while still having complete
+ date information. This is most useful when used with the `AutoDateLocator`.
+
+* `DateFormatter`: use `~datetime.datetime.strftime` format strings.
+"""
+
+import datetime
+import functools
+import logging
+import math
+import re
+
+from dateutil.rrule import (rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY,
+ MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY,
+ SECONDLY)
+from dateutil.relativedelta import relativedelta
+import dateutil.parser
+import dateutil.tz
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib import _api, cbook, ticker, units
+
+__all__ = ('datestr2num', 'date2num', 'num2date', 'num2timedelta', 'drange',
+ 'set_epoch', 'get_epoch', 'DateFormatter', 'ConciseDateFormatter',
+ 'AutoDateFormatter', 'DateLocator', 'RRuleLocator',
+ 'AutoDateLocator', 'YearLocator', 'MonthLocator', 'WeekdayLocator',
+ 'DayLocator', 'HourLocator', 'MinuteLocator',
+ 'SecondLocator', 'MicrosecondLocator',
+ 'rrule', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU',
+ 'YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY',
+ 'HOURLY', 'MINUTELY', 'SECONDLY', 'MICROSECONDLY', 'relativedelta',
+ 'DateConverter', 'ConciseDateConverter', 'rrulewrapper')
+
+
+_log = logging.getLogger(__name__)
+UTC = datetime.timezone.utc
+
+
+@_api.caching_module_getattr
+class __getattr__:
+ JULIAN_OFFSET = _api.deprecated("3.7")(property(lambda self: 1721424.5))
+ # Julian date at 0000-12-31
+ # note that the Julian day epoch is achievable w/
+ # np.datetime64('-4713-11-24T12:00:00'); datetime64 is proleptic
+ # Gregorian and BC has a one-year offset. So
+ # np.datetime64('0000-12-31') - np.datetime64('-4713-11-24T12:00') =
+ # 1721424.5
+ # Ref: https://en.wikipedia.org/wiki/Julian_day
+
+
+def _get_tzinfo(tz=None):
+ """
+ Generate `~datetime.tzinfo` from a string or return `~datetime.tzinfo`.
+ If None, retrieve the preferred timezone from the rcParams dictionary.
+ """
+ if tz is None:
+ tz = mpl.rcParams['timezone']
+ if tz == 'UTC':
+ return UTC
+ if isinstance(tz, str):
+ tzinfo = dateutil.tz.gettz(tz)
+ if tzinfo is None:
+ raise ValueError(f"{tz} is not a valid timezone as parsed by"
+ " dateutil.tz.gettz.")
+ return tzinfo
+ if isinstance(tz, datetime.tzinfo):
+ return tz
+ raise TypeError("tz must be string or tzinfo subclass.")
+
+
+# Time-related constants.
+EPOCH_OFFSET = float(datetime.datetime(1970, 1, 1).toordinal())
+# EPOCH_OFFSET is not used by matplotlib
+MICROSECONDLY = SECONDLY + 1
+HOURS_PER_DAY = 24.
+MIN_PER_HOUR = 60.
+SEC_PER_MIN = 60.
+MONTHS_PER_YEAR = 12.
+
+DAYS_PER_WEEK = 7.
+DAYS_PER_MONTH = 30.
+DAYS_PER_YEAR = 365.0
+
+MINUTES_PER_DAY = MIN_PER_HOUR * HOURS_PER_DAY
+
+SEC_PER_HOUR = SEC_PER_MIN * MIN_PER_HOUR
+SEC_PER_DAY = SEC_PER_HOUR * HOURS_PER_DAY
+SEC_PER_WEEK = SEC_PER_DAY * DAYS_PER_WEEK
+
+MUSECONDS_PER_DAY = 1e6 * SEC_PER_DAY
+
+MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY = (
+ MO, TU, WE, TH, FR, SA, SU)
+WEEKDAYS = (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY)
+
+# default epoch: passed to np.datetime64...
+_epoch = None
+
+
+def _reset_epoch_test_example():
+ """
+ Reset the Matplotlib date epoch so it can be set again.
+
+ Only for use in tests and examples.
+ """
+ global _epoch
+ _epoch = None
+
+
+def set_epoch(epoch):
+ """
+ Set the epoch (origin for dates) for datetime calculations.
+
+ The default epoch is :rc:`dates.epoch` (by default 1970-01-01T00:00).
+
+ If microsecond accuracy is desired, the date being plotted needs to be
+ within approximately 70 years of the epoch. Matplotlib internally
+ represents dates as days since the epoch, so floating point dynamic
+ range needs to be within a factor of 2^52.
+
+ `~.dates.set_epoch` must be called before any dates are converted
+ (i.e. near the import section) or a RuntimeError will be raised.
+
+ See also :doc:`/gallery/ticks/date_precision_and_epochs`.
+
+ Parameters
+ ----------
+ epoch : str
+ valid UTC date parsable by `numpy.datetime64` (do not include
+ timezone).
+
+ """
+ global _epoch
+ if _epoch is not None:
+ raise RuntimeError('set_epoch must be called before dates plotted.')
+ _epoch = epoch
+
+
+def get_epoch():
+ """
+ Get the epoch used by `.dates`.
+
+ Returns
+ -------
+ epoch : str
+ String for the epoch (parsable by `numpy.datetime64`).
+ """
+ global _epoch
+
+ if _epoch is None:
+ _epoch = mpl.rcParams['date.epoch']
+ return _epoch
+
+
+def _dt64_to_ordinalf(d):
+ """
+ Convert `numpy.datetime64` or an `numpy.ndarray` of those types to
+ Gregorian date as UTC float relative to the epoch (see `.get_epoch`).
+ Roundoff is float64 precision. Practically: microseconds for dates
+ between 290301 BC, 294241 AD, milliseconds for larger dates
+ (see `numpy.datetime64`).
+ """
+
+ # the "extra" ensures that we at least allow the dynamic range out to
+ # seconds. That should get out to +/-2e11 years.
+ dseconds = d.astype('datetime64[s]')
+ extra = (d - dseconds).astype('timedelta64[ns]')
+ t0 = np.datetime64(get_epoch(), 's')
+ dt = (dseconds - t0).astype(np.float64)
+ dt += extra.astype(np.float64) / 1.0e9
+ dt = dt / SEC_PER_DAY
+
+ NaT_int = np.datetime64('NaT').astype(np.int64)
+ d_int = d.astype(np.int64)
+ dt[d_int == NaT_int] = np.nan
+ return dt
+
+
+def _from_ordinalf(x, tz=None):
+ """
+ Convert Gregorian float of the date, preserving hours, minutes,
+ seconds and microseconds. Return value is a `.datetime`.
+
+ The input date *x* is a float in ordinal days at UTC, and the output will
+ be the specified `.datetime` object corresponding to that time in
+ timezone *tz*, or if *tz* is ``None``, in the timezone specified in
+ :rc:`timezone`.
+ """
+
+ tz = _get_tzinfo(tz)
+
+ dt = (np.datetime64(get_epoch()) +
+ np.timedelta64(int(np.round(x * MUSECONDS_PER_DAY)), 'us'))
+ if dt < np.datetime64('0001-01-01') or dt >= np.datetime64('10000-01-01'):
+ raise ValueError(f'Date ordinal {x} converts to {dt} (using '
+ f'epoch {get_epoch()}), but Matplotlib dates must be '
+ 'between year 0001 and 9999.')
+ # convert from datetime64 to datetime:
+ dt = dt.tolist()
+
+ # datetime64 is always UTC:
+ dt = dt.replace(tzinfo=dateutil.tz.gettz('UTC'))
+ # but maybe we are working in a different timezone so move.
+ dt = dt.astimezone(tz)
+ # fix round off errors
+ if np.abs(x) > 70 * 365:
+ # if x is big, round off to nearest twenty microseconds.
+ # This avoids floating point roundoff error
+ ms = round(dt.microsecond / 20) * 20
+ if ms == 1000000:
+ dt = dt.replace(microsecond=0) + datetime.timedelta(seconds=1)
+ else:
+ dt = dt.replace(microsecond=ms)
+
+ return dt
+
+
+# a version of _from_ordinalf that can operate on numpy arrays
+_from_ordinalf_np_vectorized = np.vectorize(_from_ordinalf, otypes="O")
+
+
+# a version of dateutil.parser.parse that can operate on numpy arrays
+_dateutil_parser_parse_np_vectorized = np.vectorize(dateutil.parser.parse)
+
+
+def datestr2num(d, default=None):
+ """
+ Convert a date string to a datenum using `dateutil.parser.parse`.
+
+ Parameters
+ ----------
+ d : str or sequence of str
+ The dates to convert.
+
+ default : datetime.datetime, optional
+ The default date to use when fields are missing in *d*.
+ """
+ if isinstance(d, str):
+ dt = dateutil.parser.parse(d, default=default)
+ return date2num(dt)
+ else:
+ if default is not None:
+ d = [date2num(dateutil.parser.parse(s, default=default))
+ for s in d]
+ return np.asarray(d)
+ d = np.asarray(d)
+ if not d.size:
+ return d
+ return date2num(_dateutil_parser_parse_np_vectorized(d))
+
+
+def date2num(d):
+ """
+ Convert datetime objects to Matplotlib dates.
+
+ Parameters
+ ----------
+ d : `datetime.datetime` or `numpy.datetime64` or sequences of these
+
+ Returns
+ -------
+ float or sequence of floats
+ Number of days since the epoch. See `.get_epoch` for the
+ epoch, which can be changed by :rc:`date.epoch` or `.set_epoch`. If
+ the epoch is "1970-01-01T00:00:00" (default) then noon Jan 1 1970
+ ("1970-01-01T12:00:00") returns 0.5.
+
+ Notes
+ -----
+ The Gregorian calendar is assumed; this is not universal practice.
+ For details see the module docstring.
+ """
+ # Unpack in case of e.g. Pandas or xarray object
+ d = cbook._unpack_to_numpy(d)
+
+ # make an iterable, but save state to unpack later:
+ iterable = np.iterable(d)
+ if not iterable:
+ d = [d]
+
+ masked = np.ma.is_masked(d)
+ mask = np.ma.getmask(d)
+ d = np.asarray(d)
+
+ # convert to datetime64 arrays, if not already:
+ if not np.issubdtype(d.dtype, np.datetime64):
+ # datetime arrays
+ if not d.size:
+ # deals with an empty array...
+ return d
+ tzi = getattr(d[0], 'tzinfo', None)
+ if tzi is not None:
+ # make datetime naive:
+ d = [dt.astimezone(UTC).replace(tzinfo=None) for dt in d]
+ d = np.asarray(d)
+ d = d.astype('datetime64[us]')
+
+ d = np.ma.masked_array(d, mask=mask) if masked else d
+ d = _dt64_to_ordinalf(d)
+
+ return d if iterable else d[0]
+
+
+@_api.deprecated("3.7")
+def julian2num(j):
+ """
+ Convert a Julian date (or sequence) to a Matplotlib date (or sequence).
+
+ Parameters
+ ----------
+ j : float or sequence of floats
+ Julian dates (days relative to 4713 BC Jan 1, 12:00:00 Julian
+ calendar or 4714 BC Nov 24, 12:00:00, proleptic Gregorian calendar).
+
+ Returns
+ -------
+ float or sequence of floats
+ Matplotlib dates (days relative to `.get_epoch`).
+ """
+ ep = np.datetime64(get_epoch(), 'h').astype(float) / 24.
+ ep0 = np.datetime64('0000-12-31T00:00:00', 'h').astype(float) / 24.
+ # Julian offset defined above is relative to 0000-12-31, but we need
+ # relative to our current epoch:
+ dt = __getattr__("JULIAN_OFFSET") - ep0 + ep
+ return np.subtract(j, dt) # Handles both scalar & nonscalar j.
+
+
+@_api.deprecated("3.7")
+def num2julian(n):
+ """
+ Convert a Matplotlib date (or sequence) to a Julian date (or sequence).
+
+ Parameters
+ ----------
+ n : float or sequence of floats
+ Matplotlib dates (days relative to `.get_epoch`).
+
+ Returns
+ -------
+ float or sequence of floats
+ Julian dates (days relative to 4713 BC Jan 1, 12:00:00).
+ """
+ ep = np.datetime64(get_epoch(), 'h').astype(float) / 24.
+ ep0 = np.datetime64('0000-12-31T00:00:00', 'h').astype(float) / 24.
+ # Julian offset defined above is relative to 0000-12-31, but we need
+ # relative to our current epoch:
+ dt = __getattr__("JULIAN_OFFSET") - ep0 + ep
+ return np.add(n, dt) # Handles both scalar & nonscalar j.
+
+
+def num2date(x, tz=None):
+ """
+ Convert Matplotlib dates to `~datetime.datetime` objects.
+
+ Parameters
+ ----------
+ x : float or sequence of floats
+ Number of days (fraction part represents hours, minutes, seconds)
+ since the epoch. See `.get_epoch` for the
+ epoch, which can be changed by :rc:`date.epoch` or `.set_epoch`.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Timezone of *x*. If a string, *tz* is passed to `dateutil.tz`.
+
+ Returns
+ -------
+ `~datetime.datetime` or sequence of `~datetime.datetime`
+ Dates are returned in timezone *tz*.
+
+ If *x* is a sequence, a sequence of `~datetime.datetime` objects will
+ be returned.
+
+ Notes
+ -----
+ The Gregorian calendar is assumed; this is not universal practice.
+ For details, see the module docstring.
+ """
+ tz = _get_tzinfo(tz)
+ return _from_ordinalf_np_vectorized(x, tz).tolist()
+
+
+_ordinalf_to_timedelta_np_vectorized = np.vectorize(
+ lambda x: datetime.timedelta(days=x), otypes="O")
+
+
+def num2timedelta(x):
+ """
+ Convert number of days to a `~datetime.timedelta` object.
+
+ If *x* is a sequence, a sequence of `~datetime.timedelta` objects will
+ be returned.
+
+ Parameters
+ ----------
+ x : float, sequence of floats
+ Number of days. The fraction part represents hours, minutes, seconds.
+
+ Returns
+ -------
+ `datetime.timedelta` or list[`datetime.timedelta`]
+ """
+ return _ordinalf_to_timedelta_np_vectorized(x).tolist()
+
+
+def drange(dstart, dend, delta):
+ """
+ Return a sequence of equally spaced Matplotlib dates.
+
+ The dates start at *dstart* and reach up to, but not including *dend*.
+ They are spaced by *delta*.
+
+ Parameters
+ ----------
+ dstart, dend : `~datetime.datetime`
+ The date limits.
+ delta : `datetime.timedelta`
+ Spacing of the dates.
+
+ Returns
+ -------
+ `numpy.array`
+ A list floats representing Matplotlib dates.
+
+ """
+ f1 = date2num(dstart)
+ f2 = date2num(dend)
+ step = delta.total_seconds() / SEC_PER_DAY
+
+ # calculate the difference between dend and dstart in times of delta
+ num = int(np.ceil((f2 - f1) / step))
+
+ # calculate end of the interval which will be generated
+ dinterval_end = dstart + num * delta
+
+ # ensure, that an half open interval will be generated [dstart, dend)
+ if dinterval_end >= dend:
+ # if the endpoint is greater than or equal to dend,
+ # just subtract one delta
+ dinterval_end -= delta
+ num -= 1
+
+ f2 = date2num(dinterval_end) # new float-endpoint
+ return np.linspace(f1, f2, num + 1)
+
+
+def _wrap_in_tex(text):
+ p = r'([a-zA-Z]+)'
+ ret_text = re.sub(p, r'}$\1$\\mathdefault{', text)
+
+ # Braces ensure symbols are not spaced like binary operators.
+ ret_text = ret_text.replace('-', '{-}').replace(':', '{:}')
+ # To not concatenate space between numbers.
+ ret_text = ret_text.replace(' ', r'\;')
+ ret_text = '$\\mathdefault{' + ret_text + '}$'
+ ret_text = ret_text.replace('$\\mathdefault{}$', '')
+ return ret_text
+
+
+## date tickers and formatters ###
+
+
+class DateFormatter(ticker.Formatter):
+ """
+ Format a tick (in days since the epoch) with a
+ `~datetime.datetime.strftime` format string.
+ """
+
+ def __init__(self, fmt, tz=None, *, usetex=None):
+ """
+ Parameters
+ ----------
+ fmt : str
+ `~datetime.datetime.strftime` format string
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ usetex : bool, default: :rc:`text.usetex`
+ To enable/disable the use of TeX's math mode for rendering the
+ results of the formatter.
+ """
+ self.tz = _get_tzinfo(tz)
+ self.fmt = fmt
+ self._usetex = (usetex if usetex is not None else
+ mpl.rcParams['text.usetex'])
+
+ def __call__(self, x, pos=0):
+ result = num2date(x, self.tz).strftime(self.fmt)
+ return _wrap_in_tex(result) if self._usetex else result
+
+ def set_tzinfo(self, tz):
+ self.tz = _get_tzinfo(tz)
+
+
+class ConciseDateFormatter(ticker.Formatter):
+ """
+ A `.Formatter` which attempts to figure out the best format to use for the
+ date, and to make it as compact as possible, but still be complete. This is
+ most useful when used with the `AutoDateLocator`::
+
+ >>> locator = AutoDateLocator()
+ >>> formatter = ConciseDateFormatter(locator)
+
+ Parameters
+ ----------
+ locator : `.ticker.Locator`
+ Locator that this axis is using.
+
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone, passed to `.dates.num2date`.
+
+ formats : list of 6 strings, optional
+ Format strings for 6 levels of tick labelling: mostly years,
+ months, days, hours, minutes, and seconds. Strings use
+ the same format codes as `~datetime.datetime.strftime`. Default is
+ ``['%Y', '%b', '%d', '%H:%M', '%H:%M', '%S.%f']``
+
+ zero_formats : list of 6 strings, optional
+ Format strings for tick labels that are "zeros" for a given tick
+ level. For instance, if most ticks are months, ticks around 1 Jan 2005
+ will be labeled "Dec", "2005", "Feb". The default is
+ ``['', '%Y', '%b', '%b-%d', '%H:%M', '%H:%M']``
+
+ offset_formats : list of 6 strings, optional
+ Format strings for the 6 levels that is applied to the "offset"
+ string found on the right side of an x-axis, or top of a y-axis.
+ Combined with the tick labels this should completely specify the
+ date. The default is::
+
+ ['', '%Y', '%Y-%b', '%Y-%b-%d', '%Y-%b-%d', '%Y-%b-%d %H:%M']
+
+ show_offset : bool, default: True
+ Whether to show the offset or not.
+
+ usetex : bool, default: :rc:`text.usetex`
+ To enable/disable the use of TeX's math mode for rendering the results
+ of the formatter.
+
+ Examples
+ --------
+ See :doc:`/gallery/ticks/date_concise_formatter`
+
+ .. plot::
+
+ import datetime
+ import matplotlib.dates as mdates
+
+ base = datetime.datetime(2005, 2, 1)
+ dates = np.array([base + datetime.timedelta(hours=(2 * i))
+ for i in range(732)])
+ N = len(dates)
+ np.random.seed(19680801)
+ y = np.cumsum(np.random.randn(N))
+
+ fig, ax = plt.subplots(constrained_layout=True)
+ locator = mdates.AutoDateLocator()
+ formatter = mdates.ConciseDateFormatter(locator)
+ ax.xaxis.set_major_locator(locator)
+ ax.xaxis.set_major_formatter(formatter)
+
+ ax.plot(dates, y)
+ ax.set_title('Concise Date Formatter')
+
+ """
+
+ def __init__(self, locator, tz=None, formats=None, offset_formats=None,
+ zero_formats=None, show_offset=True, *, usetex=None):
+ """
+ Autoformat the date labels. The default format is used to form an
+ initial string, and then redundant elements are removed.
+ """
+ self._locator = locator
+ self._tz = tz
+ self.defaultfmt = '%Y'
+ # there are 6 levels with each level getting a specific format
+ # 0: mostly years, 1: months, 2: days,
+ # 3: hours, 4: minutes, 5: seconds
+ if formats:
+ if len(formats) != 6:
+ raise ValueError('formats argument must be a list of '
+ '6 format strings (or None)')
+ self.formats = formats
+ else:
+ self.formats = ['%Y', # ticks are mostly years
+ '%b', # ticks are mostly months
+ '%d', # ticks are mostly days
+ '%H:%M', # hrs
+ '%H:%M', # min
+ '%S.%f', # secs
+ ]
+ # fmt for zeros ticks at this level. These are
+ # ticks that should be labeled w/ info the level above.
+ # like 1 Jan can just be labelled "Jan". 02:02:00 can
+ # just be labeled 02:02.
+ if zero_formats:
+ if len(zero_formats) != 6:
+ raise ValueError('zero_formats argument must be a list of '
+ '6 format strings (or None)')
+ self.zero_formats = zero_formats
+ elif formats:
+ # use the users formats for the zero tick formats
+ self.zero_formats = [''] + self.formats[:-1]
+ else:
+ # make the defaults a bit nicer:
+ self.zero_formats = [''] + self.formats[:-1]
+ self.zero_formats[3] = '%b-%d'
+
+ if offset_formats:
+ if len(offset_formats) != 6:
+ raise ValueError('offset_formats argument must be a list of '
+ '6 format strings (or None)')
+ self.offset_formats = offset_formats
+ else:
+ self.offset_formats = ['',
+ '%Y',
+ '%Y-%b',
+ '%Y-%b-%d',
+ '%Y-%b-%d',
+ '%Y-%b-%d %H:%M']
+ self.offset_string = ''
+ self.show_offset = show_offset
+ self._usetex = (usetex if usetex is not None else
+ mpl.rcParams['text.usetex'])
+
+ def __call__(self, x, pos=None):
+ formatter = DateFormatter(self.defaultfmt, self._tz,
+ usetex=self._usetex)
+ return formatter(x, pos=pos)
+
+ def format_ticks(self, values):
+ tickdatetime = [num2date(value, tz=self._tz) for value in values]
+ tickdate = np.array([tdt.timetuple()[:6] for tdt in tickdatetime])
+
+ # basic algorithm:
+ # 1) only display a part of the date if it changes over the ticks.
+ # 2) don't display the smaller part of the date if:
+ # it is always the same or if it is the start of the
+ # year, month, day etc.
+ # fmt for most ticks at this level
+ fmts = self.formats
+ # format beginnings of days, months, years, etc.
+ zerofmts = self.zero_formats
+ # offset fmt are for the offset in the upper left of the
+ # or lower right of the axis.
+ offsetfmts = self.offset_formats
+ show_offset = self.show_offset
+
+ # determine the level we will label at:
+ # mostly 0: years, 1: months, 2: days,
+ # 3: hours, 4: minutes, 5: seconds, 6: microseconds
+ for level in range(5, -1, -1):
+ unique = np.unique(tickdate[:, level])
+ if len(unique) > 1:
+ # if 1 is included in unique, the year is shown in ticks
+ if level < 2 and np.any(unique == 1):
+ show_offset = False
+ break
+ elif level == 0:
+ # all tickdate are the same, so only micros might be different
+ # set to the most precise (6: microseconds doesn't exist...)
+ level = 5
+
+ # level is the basic level we will label at.
+ # now loop through and decide the actual ticklabels
+ zerovals = [0, 1, 1, 0, 0, 0, 0]
+ labels = [''] * len(tickdate)
+ for nn in range(len(tickdate)):
+ if level < 5:
+ if tickdate[nn][level] == zerovals[level]:
+ fmt = zerofmts[level]
+ else:
+ fmt = fmts[level]
+ else:
+ # special handling for seconds + microseconds
+ if (tickdatetime[nn].second == tickdatetime[nn].microsecond
+ == 0):
+ fmt = zerofmts[level]
+ else:
+ fmt = fmts[level]
+ labels[nn] = tickdatetime[nn].strftime(fmt)
+
+ # special handling of seconds and microseconds:
+ # strip extra zeros and decimal if possible.
+ # this is complicated by two factors. 1) we have some level-4 strings
+ # here (i.e. 03:00, '0.50000', '1.000') 2) we would like to have the
+ # same number of decimals for each string (i.e. 0.5 and 1.0).
+ if level >= 5:
+ trailing_zeros = min(
+ (len(s) - len(s.rstrip('0')) for s in labels if '.' in s),
+ default=None)
+ if trailing_zeros:
+ for nn in range(len(labels)):
+ if '.' in labels[nn]:
+ labels[nn] = labels[nn][:-trailing_zeros].rstrip('.')
+
+ if show_offset:
+ # set the offset string:
+ self.offset_string = tickdatetime[-1].strftime(offsetfmts[level])
+ if self._usetex:
+ self.offset_string = _wrap_in_tex(self.offset_string)
+ else:
+ self.offset_string = ''
+
+ if self._usetex:
+ return [_wrap_in_tex(l) for l in labels]
+ else:
+ return labels
+
+ def get_offset(self):
+ return self.offset_string
+
+ def format_data_short(self, value):
+ return num2date(value, tz=self._tz).strftime('%Y-%m-%d %H:%M:%S')
+
+
+class AutoDateFormatter(ticker.Formatter):
+ """
+ A `.Formatter` which attempts to figure out the best format to use. This
+ is most useful when used with the `AutoDateLocator`.
+
+ `.AutoDateFormatter` has a ``.scale`` dictionary that maps tick scales (the
+ interval in days between one major tick) to format strings; this dictionary
+ defaults to ::
+
+ self.scaled = {
+ DAYS_PER_YEAR: rcParams['date.autoformatter.year'],
+ DAYS_PER_MONTH: rcParams['date.autoformatter.month'],
+ 1: rcParams['date.autoformatter.day'],
+ 1 / HOURS_PER_DAY: rcParams['date.autoformatter.hour'],
+ 1 / MINUTES_PER_DAY: rcParams['date.autoformatter.minute'],
+ 1 / SEC_PER_DAY: rcParams['date.autoformatter.second'],
+ 1 / MUSECONDS_PER_DAY: rcParams['date.autoformatter.microsecond'],
+ }
+
+ The formatter uses the format string corresponding to the lowest key in
+ the dictionary that is greater or equal to the current scale. Dictionary
+ entries can be customized::
+
+ locator = AutoDateLocator()
+ formatter = AutoDateFormatter(locator)
+ formatter.scaled[1/(24*60)] = '%M:%S' # only show min and sec
+
+ Custom callables can also be used instead of format strings. The following
+ example shows how to use a custom format function to strip trailing zeros
+ from decimal seconds and adds the date to the first ticklabel::
+
+ def my_format_function(x, pos=None):
+ x = matplotlib.dates.num2date(x)
+ if pos == 0:
+ fmt = '%D %H:%M:%S.%f'
+ else:
+ fmt = '%H:%M:%S.%f'
+ label = x.strftime(fmt)
+ label = label.rstrip("0")
+ label = label.rstrip(".")
+ return label
+
+ formatter.scaled[1/(24*60)] = my_format_function
+ """
+
+ # This can be improved by providing some user-level direction on
+ # how to choose the best format (precedence, etc.).
+
+ # Perhaps a 'struct' that has a field for each time-type where a
+ # zero would indicate "don't show" and a number would indicate
+ # "show" with some sort of priority. Same priorities could mean
+ # show all with the same priority.
+
+ # Or more simply, perhaps just a format string for each
+ # possibility...
+
+ def __init__(self, locator, tz=None, defaultfmt='%Y-%m-%d', *,
+ usetex=None):
+ """
+ Autoformat the date labels.
+
+ Parameters
+ ----------
+ locator : `.ticker.Locator`
+ Locator that this axis is using.
+
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+
+ defaultfmt : str
+ The default format to use if none of the values in ``self.scaled``
+ are greater than the unit returned by ``locator._get_unit()``.
+
+ usetex : bool, default: :rc:`text.usetex`
+ To enable/disable the use of TeX's math mode for rendering the
+ results of the formatter. If any entries in ``self.scaled`` are set
+ as functions, then it is up to the customized function to enable or
+ disable TeX's math mode itself.
+ """
+ self._locator = locator
+ self._tz = tz
+ self.defaultfmt = defaultfmt
+ self._formatter = DateFormatter(self.defaultfmt, tz)
+ rcParams = mpl.rcParams
+ self._usetex = (usetex if usetex is not None else
+ mpl.rcParams['text.usetex'])
+ self.scaled = {
+ DAYS_PER_YEAR: rcParams['date.autoformatter.year'],
+ DAYS_PER_MONTH: rcParams['date.autoformatter.month'],
+ 1: rcParams['date.autoformatter.day'],
+ 1 / HOURS_PER_DAY: rcParams['date.autoformatter.hour'],
+ 1 / MINUTES_PER_DAY: rcParams['date.autoformatter.minute'],
+ 1 / SEC_PER_DAY: rcParams['date.autoformatter.second'],
+ 1 / MUSECONDS_PER_DAY: rcParams['date.autoformatter.microsecond']
+ }
+
+ def _set_locator(self, locator):
+ self._locator = locator
+
+ def __call__(self, x, pos=None):
+ try:
+ locator_unit_scale = float(self._locator._get_unit())
+ except AttributeError:
+ locator_unit_scale = 1
+ # Pick the first scale which is greater than the locator unit.
+ fmt = next((fmt for scale, fmt in sorted(self.scaled.items())
+ if scale >= locator_unit_scale),
+ self.defaultfmt)
+
+ if isinstance(fmt, str):
+ self._formatter = DateFormatter(fmt, self._tz, usetex=self._usetex)
+ result = self._formatter(x, pos)
+ elif callable(fmt):
+ result = fmt(x, pos)
+ else:
+ raise TypeError('Unexpected type passed to {0!r}.'.format(self))
+
+ return result
+
+
+class rrulewrapper:
+ """
+ A simple wrapper around a `dateutil.rrule` allowing flexible
+ date tick specifications.
+ """
+ def __init__(self, freq, tzinfo=None, **kwargs):
+ """
+ Parameters
+ ----------
+ freq : {YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY}
+ Tick frequency. These constants are defined in `dateutil.rrule`,
+ but they are accessible from `matplotlib.dates` as well.
+ tzinfo : `datetime.tzinfo`, optional
+ Time zone information. The default is None.
+ **kwargs
+ Additional keyword arguments are passed to the `dateutil.rrule`.
+ """
+ kwargs['freq'] = freq
+ self._base_tzinfo = tzinfo
+
+ self._update_rrule(**kwargs)
+
+ def set(self, **kwargs):
+ """Set parameters for an existing wrapper."""
+ self._construct.update(kwargs)
+
+ self._update_rrule(**self._construct)
+
+ def _update_rrule(self, **kwargs):
+ tzinfo = self._base_tzinfo
+
+ # rrule does not play nicely with timezones - especially pytz time
+ # zones, it's best to use naive zones and attach timezones once the
+ # datetimes are returned
+ if 'dtstart' in kwargs:
+ dtstart = kwargs['dtstart']
+ if dtstart.tzinfo is not None:
+ if tzinfo is None:
+ tzinfo = dtstart.tzinfo
+ else:
+ dtstart = dtstart.astimezone(tzinfo)
+
+ kwargs['dtstart'] = dtstart.replace(tzinfo=None)
+
+ if 'until' in kwargs:
+ until = kwargs['until']
+ if until.tzinfo is not None:
+ if tzinfo is not None:
+ until = until.astimezone(tzinfo)
+ else:
+ raise ValueError('until cannot be aware if dtstart '
+ 'is naive and tzinfo is None')
+
+ kwargs['until'] = until.replace(tzinfo=None)
+
+ self._construct = kwargs.copy()
+ self._tzinfo = tzinfo
+ self._rrule = rrule(**self._construct)
+
+ def _attach_tzinfo(self, dt, tzinfo):
+ # pytz zones are attached by "localizing" the datetime
+ if hasattr(tzinfo, 'localize'):
+ return tzinfo.localize(dt, is_dst=True)
+
+ return dt.replace(tzinfo=tzinfo)
+
+ def _aware_return_wrapper(self, f, returns_list=False):
+ """Decorator function that allows rrule methods to handle tzinfo."""
+ # This is only necessary if we're actually attaching a tzinfo
+ if self._tzinfo is None:
+ return f
+
+ # All datetime arguments must be naive. If they are not naive, they are
+ # converted to the _tzinfo zone before dropping the zone.
+ def normalize_arg(arg):
+ if isinstance(arg, datetime.datetime) and arg.tzinfo is not None:
+ if arg.tzinfo is not self._tzinfo:
+ arg = arg.astimezone(self._tzinfo)
+
+ return arg.replace(tzinfo=None)
+
+ return arg
+
+ def normalize_args(args, kwargs):
+ args = tuple(normalize_arg(arg) for arg in args)
+ kwargs = {kw: normalize_arg(arg) for kw, arg in kwargs.items()}
+
+ return args, kwargs
+
+ # There are two kinds of functions we care about - ones that return
+ # dates and ones that return lists of dates.
+ if not returns_list:
+ def inner_func(*args, **kwargs):
+ args, kwargs = normalize_args(args, kwargs)
+ dt = f(*args, **kwargs)
+ return self._attach_tzinfo(dt, self._tzinfo)
+ else:
+ def inner_func(*args, **kwargs):
+ args, kwargs = normalize_args(args, kwargs)
+ dts = f(*args, **kwargs)
+ return [self._attach_tzinfo(dt, self._tzinfo) for dt in dts]
+
+ return functools.wraps(f)(inner_func)
+
+ def __getattr__(self, name):
+ if name in self.__dict__:
+ return self.__dict__[name]
+
+ f = getattr(self._rrule, name)
+
+ if name in {'after', 'before'}:
+ return self._aware_return_wrapper(f)
+ elif name in {'xafter', 'xbefore', 'between'}:
+ return self._aware_return_wrapper(f, returns_list=True)
+ else:
+ return f
+
+ def __setstate__(self, state):
+ self.__dict__.update(state)
+
+
+class DateLocator(ticker.Locator):
+ """
+ Determines the tick locations when plotting dates.
+
+ This class is subclassed by other Locators and
+ is not meant to be used on its own.
+ """
+ hms0d = {'byhour': 0, 'byminute': 0, 'bysecond': 0}
+
+ def __init__(self, tz=None):
+ """
+ Parameters
+ ----------
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ self.tz = _get_tzinfo(tz)
+
+ def set_tzinfo(self, tz):
+ """
+ Set timezone info.
+
+ Parameters
+ ----------
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ self.tz = _get_tzinfo(tz)
+
+ def datalim_to_dt(self):
+ """Convert axis data interval to datetime objects."""
+ dmin, dmax = self.axis.get_data_interval()
+ if dmin > dmax:
+ dmin, dmax = dmax, dmin
+
+ return num2date(dmin, self.tz), num2date(dmax, self.tz)
+
+ def viewlim_to_dt(self):
+ """Convert the view interval to datetime objects."""
+ vmin, vmax = self.axis.get_view_interval()
+ if vmin > vmax:
+ vmin, vmax = vmax, vmin
+ return num2date(vmin, self.tz), num2date(vmax, self.tz)
+
+ def _get_unit(self):
+ """
+ Return how many days a unit of the locator is; used for
+ intelligent autoscaling.
+ """
+ return 1
+
+ def _get_interval(self):
+ """
+ Return the number of units for each tick.
+ """
+ return 1
+
+ def nonsingular(self, vmin, vmax):
+ """
+ Given the proposed upper and lower extent, adjust the range
+ if it is too close to being singular (i.e. a range of ~0).
+ """
+ if not np.isfinite(vmin) or not np.isfinite(vmax):
+ # Except if there is no data, then use 1970 as default.
+ return (date2num(datetime.date(1970, 1, 1)),
+ date2num(datetime.date(1970, 1, 2)))
+ if vmax < vmin:
+ vmin, vmax = vmax, vmin
+ unit = self._get_unit()
+ interval = self._get_interval()
+ if abs(vmax - vmin) < 1e-6:
+ vmin -= 2 * unit * interval
+ vmax += 2 * unit * interval
+ return vmin, vmax
+
+
+class RRuleLocator(DateLocator):
+ # use the dateutil rrule instance
+
+ def __init__(self, o, tz=None):
+ super().__init__(tz)
+ self.rule = o
+
+ def __call__(self):
+ # if no data have been set, this will tank with a ValueError
+ try:
+ dmin, dmax = self.viewlim_to_dt()
+ except ValueError:
+ return []
+
+ return self.tick_values(dmin, dmax)
+
+ def tick_values(self, vmin, vmax):
+ start, stop = self._create_rrule(vmin, vmax)
+ dates = self.rule.between(start, stop, True)
+ if len(dates) == 0:
+ return date2num([vmin, vmax])
+ return self.raise_if_exceeds(date2num(dates))
+
+ def _create_rrule(self, vmin, vmax):
+ # set appropriate rrule dtstart and until and return
+ # start and end
+ delta = relativedelta(vmax, vmin)
+
+ # We need to cap at the endpoints of valid datetime
+ try:
+ start = vmin - delta
+ except (ValueError, OverflowError):
+ # cap
+ start = datetime.datetime(1, 1, 1, 0, 0, 0,
+ tzinfo=datetime.timezone.utc)
+
+ try:
+ stop = vmax + delta
+ except (ValueError, OverflowError):
+ # cap
+ stop = datetime.datetime(9999, 12, 31, 23, 59, 59,
+ tzinfo=datetime.timezone.utc)
+
+ self.rule.set(dtstart=start, until=stop)
+
+ return vmin, vmax
+
+ def _get_unit(self):
+ # docstring inherited
+ freq = self.rule._rrule._freq
+ return self.get_unit_generic(freq)
+
+ @staticmethod
+ def get_unit_generic(freq):
+ if freq == YEARLY:
+ return DAYS_PER_YEAR
+ elif freq == MONTHLY:
+ return DAYS_PER_MONTH
+ elif freq == WEEKLY:
+ return DAYS_PER_WEEK
+ elif freq == DAILY:
+ return 1.0
+ elif freq == HOURLY:
+ return 1.0 / HOURS_PER_DAY
+ elif freq == MINUTELY:
+ return 1.0 / MINUTES_PER_DAY
+ elif freq == SECONDLY:
+ return 1.0 / SEC_PER_DAY
+ else:
+ # error
+ return -1 # or should this just return '1'?
+
+ def _get_interval(self):
+ return self.rule._rrule._interval
+
+
+class AutoDateLocator(DateLocator):
+ """
+ On autoscale, this class picks the best `DateLocator` to set the view
+ limits and the tick locations.
+
+ Attributes
+ ----------
+ intervald : dict
+
+ Mapping of tick frequencies to multiples allowed for that ticking.
+ The default is ::
+
+ self.intervald = {
+ YEARLY : [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500,
+ 1000, 2000, 4000, 5000, 10000],
+ MONTHLY : [1, 2, 3, 4, 6],
+ DAILY : [1, 2, 3, 7, 14, 21],
+ HOURLY : [1, 2, 3, 4, 6, 12],
+ MINUTELY: [1, 5, 10, 15, 30],
+ SECONDLY: [1, 5, 10, 15, 30],
+ MICROSECONDLY: [1, 2, 5, 10, 20, 50, 100, 200, 500,
+ 1000, 2000, 5000, 10000, 20000, 50000,
+ 100000, 200000, 500000, 1000000],
+ }
+
+ where the keys are defined in `dateutil.rrule`.
+
+ The interval is used to specify multiples that are appropriate for
+ the frequency of ticking. For instance, every 7 days is sensible
+ for daily ticks, but for minutes/seconds, 15 or 30 make sense.
+
+ When customizing, you should only modify the values for the existing
+ keys. You should not add or delete entries.
+
+ Example for forcing ticks every 3 hours::
+
+ locator = AutoDateLocator()
+ locator.intervald[HOURLY] = [3] # only show every 3 hours
+ """
+
+ def __init__(self, tz=None, minticks=5, maxticks=None,
+ interval_multiples=True):
+ """
+ Parameters
+ ----------
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ minticks : int
+ The minimum number of ticks desired; controls whether ticks occur
+ yearly, monthly, etc.
+ maxticks : int
+ The maximum number of ticks desired; controls the interval between
+ ticks (ticking every other, every 3, etc.). For fine-grained
+ control, this can be a dictionary mapping individual rrule
+ frequency constants (YEARLY, MONTHLY, etc.) to their own maximum
+ number of ticks. This can be used to keep the number of ticks
+ appropriate to the format chosen in `AutoDateFormatter`. Any
+ frequency not specified in this dictionary is given a default
+ value.
+ interval_multiples : bool, default: True
+ Whether ticks should be chosen to be multiple of the interval,
+ locking them to 'nicer' locations. For example, this will force
+ the ticks to be at hours 0, 6, 12, 18 when hourly ticking is done
+ at 6 hour intervals.
+ """
+ super().__init__(tz=tz)
+ self._freq = YEARLY
+ self._freqs = [YEARLY, MONTHLY, DAILY, HOURLY, MINUTELY,
+ SECONDLY, MICROSECONDLY]
+ self.minticks = minticks
+
+ self.maxticks = {YEARLY: 11, MONTHLY: 12, DAILY: 11, HOURLY: 12,
+ MINUTELY: 11, SECONDLY: 11, MICROSECONDLY: 8}
+ if maxticks is not None:
+ try:
+ self.maxticks.update(maxticks)
+ except TypeError:
+ # Assume we were given an integer. Use this as the maximum
+ # number of ticks for every frequency and create a
+ # dictionary for this
+ self.maxticks = dict.fromkeys(self._freqs, maxticks)
+ self.interval_multiples = interval_multiples
+ self.intervald = {
+ YEARLY: [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500,
+ 1000, 2000, 4000, 5000, 10000],
+ MONTHLY: [1, 2, 3, 4, 6],
+ DAILY: [1, 2, 3, 7, 14, 21],
+ HOURLY: [1, 2, 3, 4, 6, 12],
+ MINUTELY: [1, 5, 10, 15, 30],
+ SECONDLY: [1, 5, 10, 15, 30],
+ MICROSECONDLY: [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000,
+ 5000, 10000, 20000, 50000, 100000, 200000, 500000,
+ 1000000],
+ }
+ if interval_multiples:
+ # Swap "3" for "4" in the DAILY list; If we use 3 we get bad
+ # tick loc for months w/ 31 days: 1, 4, ..., 28, 31, 1
+ # If we use 4 then we get: 1, 5, ... 25, 29, 1
+ self.intervald[DAILY] = [1, 2, 4, 7, 14]
+
+ self._byranges = [None, range(1, 13), range(1, 32),
+ range(0, 24), range(0, 60), range(0, 60), None]
+
+ def __call__(self):
+ # docstring inherited
+ dmin, dmax = self.viewlim_to_dt()
+ locator = self.get_locator(dmin, dmax)
+ return locator()
+
+ def tick_values(self, vmin, vmax):
+ return self.get_locator(vmin, vmax).tick_values(vmin, vmax)
+
+ def nonsingular(self, vmin, vmax):
+ # whatever is thrown at us, we can scale the unit.
+ # But default nonsingular date plots at an ~4 year period.
+ if not np.isfinite(vmin) or not np.isfinite(vmax):
+ # Except if there is no data, then use 1970 as default.
+ return (date2num(datetime.date(1970, 1, 1)),
+ date2num(datetime.date(1970, 1, 2)))
+ if vmax < vmin:
+ vmin, vmax = vmax, vmin
+ if vmin == vmax:
+ vmin = vmin - DAYS_PER_YEAR * 2
+ vmax = vmax + DAYS_PER_YEAR * 2
+ return vmin, vmax
+
+ def _get_unit(self):
+ if self._freq in [MICROSECONDLY]:
+ return 1. / MUSECONDS_PER_DAY
+ else:
+ return RRuleLocator.get_unit_generic(self._freq)
+
+ def get_locator(self, dmin, dmax):
+ """Pick the best locator based on a distance."""
+ delta = relativedelta(dmax, dmin)
+ tdelta = dmax - dmin
+
+ # take absolute difference
+ if dmin > dmax:
+ delta = -delta
+ tdelta = -tdelta
+ # The following uses a mix of calls to relativedelta and timedelta
+ # methods because there is incomplete overlap in the functionality of
+ # these similar functions, and it's best to avoid doing our own math
+ # whenever possible.
+ numYears = float(delta.years)
+ numMonths = numYears * MONTHS_PER_YEAR + delta.months
+ numDays = tdelta.days # Avoids estimates of days/month, days/year.
+ numHours = numDays * HOURS_PER_DAY + delta.hours
+ numMinutes = numHours * MIN_PER_HOUR + delta.minutes
+ numSeconds = np.floor(tdelta.total_seconds())
+ numMicroseconds = np.floor(tdelta.total_seconds() * 1e6)
+
+ nums = [numYears, numMonths, numDays, numHours, numMinutes,
+ numSeconds, numMicroseconds]
+
+ use_rrule_locator = [True] * 6 + [False]
+
+ # Default setting of bymonth, etc. to pass to rrule
+ # [unused (for year), bymonth, bymonthday, byhour, byminute,
+ # bysecond, unused (for microseconds)]
+ byranges = [None, 1, 1, 0, 0, 0, None]
+
+ # Loop over all the frequencies and try to find one that gives at
+ # least a minticks tick positions. Once this is found, look for
+ # an interval from a list specific to that frequency that gives no
+ # more than maxticks tick positions. Also, set up some ranges
+ # (bymonth, etc.) as appropriate to be passed to rrulewrapper.
+ for i, (freq, num) in enumerate(zip(self._freqs, nums)):
+ # If this particular frequency doesn't give enough ticks, continue
+ if num < self.minticks:
+ # Since we're not using this particular frequency, set
+ # the corresponding by_ to None so the rrule can act as
+ # appropriate
+ byranges[i] = None
+ continue
+
+ # Find the first available interval that doesn't give too many
+ # ticks
+ for interval in self.intervald[freq]:
+ if num <= interval * (self.maxticks[freq] - 1):
+ break
+ else:
+ if not (self.interval_multiples and freq == DAILY):
+ _api.warn_external(
+ f"AutoDateLocator was unable to pick an appropriate "
+ f"interval for this date range. It may be necessary "
+ f"to add an interval value to the AutoDateLocator's "
+ f"intervald dictionary. Defaulting to {interval}.")
+
+ # Set some parameters as appropriate
+ self._freq = freq
+
+ if self._byranges[i] and self.interval_multiples:
+ byranges[i] = self._byranges[i][::interval]
+ if i in (DAILY, WEEKLY):
+ if interval == 14:
+ # just make first and 15th. Avoids 30th.
+ byranges[i] = [1, 15]
+ elif interval == 7:
+ byranges[i] = [1, 8, 15, 22]
+
+ interval = 1
+ else:
+ byranges[i] = self._byranges[i]
+ break
+ else:
+ interval = 1
+
+ if (freq == YEARLY) and self.interval_multiples:
+ locator = YearLocator(interval, tz=self.tz)
+ elif use_rrule_locator[i]:
+ _, bymonth, bymonthday, byhour, byminute, bysecond, _ = byranges
+ rrule = rrulewrapper(self._freq, interval=interval,
+ dtstart=dmin, until=dmax,
+ bymonth=bymonth, bymonthday=bymonthday,
+ byhour=byhour, byminute=byminute,
+ bysecond=bysecond)
+
+ locator = RRuleLocator(rrule, tz=self.tz)
+ else:
+ locator = MicrosecondLocator(interval, tz=self.tz)
+ if date2num(dmin) > 70 * 365 and interval < 1000:
+ _api.warn_external(
+ 'Plotting microsecond time intervals for dates far from '
+ f'the epoch (time origin: {get_epoch()}) is not well-'
+ 'supported. See matplotlib.dates.set_epoch to change the '
+ 'epoch.')
+
+ locator.set_axis(self.axis)
+ return locator
+
+
+class YearLocator(RRuleLocator):
+ """
+ Make ticks on a given day of each year that is a multiple of base.
+
+ Examples::
+
+ # Tick every year on Jan 1st
+ locator = YearLocator()
+
+ # Tick every 5 years on July 4th
+ locator = YearLocator(5, month=7, day=4)
+ """
+ def __init__(self, base=1, month=1, day=1, tz=None):
+ """
+ Parameters
+ ----------
+ base : int, default: 1
+ Mark ticks every *base* years.
+ month : int, default: 1
+ The month on which to place the ticks, starting from 1. Default is
+ January.
+ day : int, default: 1
+ The day on which to place the ticks.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ rule = rrulewrapper(YEARLY, interval=base, bymonth=month,
+ bymonthday=day, **self.hms0d)
+ super().__init__(rule, tz=tz)
+ self.base = ticker._Edge_integer(base, 0)
+
+ def _create_rrule(self, vmin, vmax):
+ # 'start' needs to be a multiple of the interval to create ticks on
+ # interval multiples when the tick frequency is YEARLY
+ ymin = max(self.base.le(vmin.year) * self.base.step, 1)
+ ymax = min(self.base.ge(vmax.year) * self.base.step, 9999)
+
+ c = self.rule._construct
+ replace = {'year': ymin,
+ 'month': c.get('bymonth', 1),
+ 'day': c.get('bymonthday', 1),
+ 'hour': 0, 'minute': 0, 'second': 0}
+
+ start = vmin.replace(**replace)
+ stop = start.replace(year=ymax)
+ self.rule.set(dtstart=start, until=stop)
+
+ return start, stop
+
+
+class MonthLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each month, e.g., 1, 3, 12.
+ """
+ def __init__(self, bymonth=None, bymonthday=1, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ bymonth : int or list of int, default: all months
+ Ticks will be placed on every month in *bymonth*. Default is
+ ``range(1, 13)``, i.e. every month.
+ bymonthday : int, default: 1
+ The day on which to place the ticks.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ if bymonth is None:
+ bymonth = range(1, 13)
+
+ rule = rrulewrapper(MONTHLY, bymonth=bymonth, bymonthday=bymonthday,
+ interval=interval, **self.hms0d)
+ super().__init__(rule, tz=tz)
+
+
+class WeekdayLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each weekday.
+ """
+
+ def __init__(self, byweekday=1, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ byweekday : int or list of int, default: all days
+ Ticks will be placed on every weekday in *byweekday*. Default is
+ every day.
+
+ Elements of *byweekday* must be one of MO, TU, WE, TH, FR, SA,
+ SU, the constants from :mod:`dateutil.rrule`, which have been
+ imported into the :mod:`matplotlib.dates` namespace.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ rule = rrulewrapper(DAILY, byweekday=byweekday,
+ interval=interval, **self.hms0d)
+ super().__init__(rule, tz=tz)
+
+
+class DayLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each day of the month. For example,
+ 1, 15, 30.
+ """
+ def __init__(self, bymonthday=None, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ bymonthday : int or list of int, default: all days
+ Ticks will be placed on every day in *bymonthday*. Default is
+ ``bymonthday=range(1, 32)``, i.e., every day of the month.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ if interval != int(interval) or interval < 1:
+ raise ValueError("interval must be an integer greater than 0")
+ if bymonthday is None:
+ bymonthday = range(1, 32)
+
+ rule = rrulewrapper(DAILY, bymonthday=bymonthday,
+ interval=interval, **self.hms0d)
+ super().__init__(rule, tz=tz)
+
+
+class HourLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each hour.
+ """
+ def __init__(self, byhour=None, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ byhour : int or list of int, default: all hours
+ Ticks will be placed on every hour in *byhour*. Default is
+ ``byhour=range(24)``, i.e., every hour.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ if byhour is None:
+ byhour = range(24)
+
+ rule = rrulewrapper(HOURLY, byhour=byhour, interval=interval,
+ byminute=0, bysecond=0)
+ super().__init__(rule, tz=tz)
+
+
+class MinuteLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each minute.
+ """
+ def __init__(self, byminute=None, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ byminute : int or list of int, default: all minutes
+ Ticks will be placed on every minute in *byminute*. Default is
+ ``byminute=range(60)``, i.e., every minute.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ if byminute is None:
+ byminute = range(60)
+
+ rule = rrulewrapper(MINUTELY, byminute=byminute, interval=interval,
+ bysecond=0)
+ super().__init__(rule, tz=tz)
+
+
+class SecondLocator(RRuleLocator):
+ """
+ Make ticks on occurrences of each second.
+ """
+ def __init__(self, bysecond=None, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ bysecond : int or list of int, default: all seconds
+ Ticks will be placed on every second in *bysecond*. Default is
+ ``bysecond = range(60)``, i.e., every second.
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ if bysecond is None:
+ bysecond = range(60)
+
+ rule = rrulewrapper(SECONDLY, bysecond=bysecond, interval=interval)
+ super().__init__(rule, tz=tz)
+
+
+class MicrosecondLocator(DateLocator):
+ """
+ Make ticks on regular intervals of one or more microsecond(s).
+
+ .. note::
+
+ By default, Matplotlib uses a floating point representation of time in
+ days since the epoch, so plotting data with
+ microsecond time resolution does not work well for
+ dates that are far (about 70 years) from the epoch (check with
+ `~.dates.get_epoch`).
+
+ If you want sub-microsecond resolution time plots, it is strongly
+ recommended to use floating point seconds, not datetime-like
+ time representation.
+
+ If you really must use datetime.datetime() or similar and still
+ need microsecond precision, change the time origin via
+ `.dates.set_epoch` to something closer to the dates being plotted.
+ See :doc:`/gallery/ticks/date_precision_and_epochs`.
+
+ """
+ def __init__(self, interval=1, tz=None):
+ """
+ Parameters
+ ----------
+ interval : int, default: 1
+ The interval between each iteration. For example, if
+ ``interval=2``, mark every second occurrence.
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
+ """
+ super().__init__(tz=tz)
+ self._interval = interval
+ self._wrapped_locator = ticker.MultipleLocator(interval)
+
+ def set_axis(self, axis):
+ self._wrapped_locator.set_axis(axis)
+ return super().set_axis(axis)
+
+ def __call__(self):
+ # if no data have been set, this will tank with a ValueError
+ try:
+ dmin, dmax = self.viewlim_to_dt()
+ except ValueError:
+ return []
+
+ return self.tick_values(dmin, dmax)
+
+ def tick_values(self, vmin, vmax):
+ nmin, nmax = date2num((vmin, vmax))
+ t0 = np.floor(nmin)
+ nmax = nmax - t0
+ nmin = nmin - t0
+ nmin *= MUSECONDS_PER_DAY
+ nmax *= MUSECONDS_PER_DAY
+
+ ticks = self._wrapped_locator.tick_values(nmin, nmax)
+
+ ticks = ticks / MUSECONDS_PER_DAY + t0
+ return ticks
+
+ def _get_unit(self):
+ # docstring inherited
+ return 1. / MUSECONDS_PER_DAY
+
+ def _get_interval(self):
+ # docstring inherited
+ return self._interval
+
+
+@_api.deprecated("3.6", alternative="`AutoDateLocator` and `AutoDateFormatter`"
+ " or vendor the code")
+def date_ticker_factory(span, tz=None, numticks=5):
+ """
+ Create a date locator with *numticks* (approx) and a date formatter
+ for *span* in days. Return value is (locator, formatter).
+ """
+
+ if span == 0:
+ span = 1 / HOURS_PER_DAY
+
+ mins = span * MINUTES_PER_DAY
+ hrs = span * HOURS_PER_DAY
+ days = span
+ wks = span / DAYS_PER_WEEK
+ months = span / DAYS_PER_MONTH # Approx
+ years = span / DAYS_PER_YEAR # Approx
+
+ if years > numticks:
+ locator = YearLocator(int(years / numticks), tz=tz) # define
+ fmt = '%Y'
+ elif months > numticks:
+ locator = MonthLocator(tz=tz)
+ fmt = '%b %Y'
+ elif wks > numticks:
+ locator = WeekdayLocator(tz=tz)
+ fmt = '%a, %b %d'
+ elif days > numticks:
+ locator = DayLocator(interval=math.ceil(days / numticks), tz=tz)
+ fmt = '%b %d'
+ elif hrs > numticks:
+ locator = HourLocator(interval=math.ceil(hrs / numticks), tz=tz)
+ fmt = '%H:%M\n%b %d'
+ elif mins > numticks:
+ locator = MinuteLocator(interval=math.ceil(mins / numticks), tz=tz)
+ fmt = '%H:%M:%S'
+ else:
+ locator = MinuteLocator(tz=tz)
+ fmt = '%H:%M:%S'
+
+ formatter = DateFormatter(fmt, tz=tz)
+ return locator, formatter
+
+
+class DateConverter(units.ConversionInterface):
+ """
+ Converter for `datetime.date` and `datetime.datetime` data, or for
+ date/time data represented as it would be converted by `date2num`.
+
+ The 'unit' tag for such data is None or a `~datetime.tzinfo` instance.
+ """
+
+ def __init__(self, *, interval_multiples=True):
+ self._interval_multiples = interval_multiples
+ super().__init__()
+
+ def axisinfo(self, unit, axis):
+ """
+ Return the `~matplotlib.units.AxisInfo` for *unit*.
+
+ *unit* is a `~datetime.tzinfo` instance or None.
+ The *axis* argument is required but not used.
+ """
+ tz = unit
+
+ majloc = AutoDateLocator(tz=tz,
+ interval_multiples=self._interval_multiples)
+ majfmt = AutoDateFormatter(majloc, tz=tz)
+ datemin = datetime.date(1970, 1, 1)
+ datemax = datetime.date(1970, 1, 2)
+
+ return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='',
+ default_limits=(datemin, datemax))
+
+ @staticmethod
+ def convert(value, unit, axis):
+ """
+ If *value* is not already a number or sequence of numbers, convert it
+ with `date2num`.
+
+ The *unit* and *axis* arguments are not used.
+ """
+ return date2num(value)
+
+ @staticmethod
+ def default_units(x, axis):
+ """
+ Return the `~datetime.tzinfo` instance of *x* or of its first element,
+ or None
+ """
+ if isinstance(x, np.ndarray):
+ x = x.ravel()
+
+ try:
+ x = cbook._safe_first_finite(x)
+ except (TypeError, StopIteration):
+ pass
+
+ try:
+ return x.tzinfo
+ except AttributeError:
+ pass
+ return None
+
+
+class ConciseDateConverter(DateConverter):
+ # docstring inherited
+
+ def __init__(self, formats=None, zero_formats=None, offset_formats=None,
+ show_offset=True, *, interval_multiples=True):
+ self._formats = formats
+ self._zero_formats = zero_formats
+ self._offset_formats = offset_formats
+ self._show_offset = show_offset
+ self._interval_multiples = interval_multiples
+ super().__init__()
+
+ def axisinfo(self, unit, axis):
+ # docstring inherited
+ tz = unit
+ majloc = AutoDateLocator(tz=tz,
+ interval_multiples=self._interval_multiples)
+ majfmt = ConciseDateFormatter(majloc, tz=tz, formats=self._formats,
+ zero_formats=self._zero_formats,
+ offset_formats=self._offset_formats,
+ show_offset=self._show_offset)
+ datemin = datetime.date(1970, 1, 1)
+ datemax = datetime.date(1970, 1, 2)
+ return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='',
+ default_limits=(datemin, datemax))
+
+
+class _SwitchableDateConverter:
+ """
+ Helper converter-like object that generates and dispatches to
+ temporary ConciseDateConverter or DateConverter instances based on
+ :rc:`date.converter` and :rc:`date.interval_multiples`.
+ """
+
+ @staticmethod
+ def _get_converter():
+ converter_cls = {
+ "concise": ConciseDateConverter, "auto": DateConverter}[
+ mpl.rcParams["date.converter"]]
+ interval_multiples = mpl.rcParams["date.interval_multiples"]
+ return converter_cls(interval_multiples=interval_multiples)
+
+ def axisinfo(self, *args, **kwargs):
+ return self._get_converter().axisinfo(*args, **kwargs)
+
+ def default_units(self, *args, **kwargs):
+ return self._get_converter().default_units(*args, **kwargs)
+
+ def convert(self, *args, **kwargs):
+ return self._get_converter().convert(*args, **kwargs)
+
+
+units.registry[np.datetime64] = \
+ units.registry[datetime.date] = \
+ units.registry[datetime.datetime] = \
+ _SwitchableDateConverter()
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/dviread.py b/omnilmm/lib/python3.10/site-packages/matplotlib/dviread.py
new file mode 100644
index 0000000000000000000000000000000000000000..a37a606139036525bad7d23e07472cdb833eba26
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/dviread.py
@@ -0,0 +1,1165 @@
+"""
+A module for reading dvi files output by TeX. Several limitations make
+this not (currently) useful as a general-purpose dvi preprocessor, but
+it is currently used by the pdf backend for processing usetex text.
+
+Interface::
+
+ with Dvi(filename, 72) as dvi:
+ # iterate over pages:
+ for page in dvi:
+ w, h, d = page.width, page.height, page.descent
+ for x, y, font, glyph, width in page.text:
+ fontname = font.texname
+ pointsize = font.size
+ ...
+ for x, y, height, width in page.boxes:
+ ...
+"""
+
+from collections import namedtuple
+import enum
+from functools import lru_cache, partial, wraps
+import logging
+import os
+from pathlib import Path
+import re
+import struct
+import subprocess
+import sys
+
+import numpy as np
+
+from matplotlib import _api, cbook
+
+_log = logging.getLogger(__name__)
+
+# Many dvi related files are looked for by external processes, require
+# additional parsing, and are used many times per rendering, which is why they
+# are cached using lru_cache().
+
+# Dvi is a bytecode format documented in
+# https://ctan.org/pkg/dvitype
+# https://texdoc.org/serve/dvitype.pdf/0
+#
+# The file consists of a preamble, some number of pages, a postamble,
+# and a finale. Different opcodes are allowed in different contexts,
+# so the Dvi object has a parser state:
+#
+# pre: expecting the preamble
+# outer: between pages (followed by a page or the postamble,
+# also e.g. font definitions are allowed)
+# page: processing a page
+# post_post: state after the postamble (our current implementation
+# just stops reading)
+# finale: the finale (unimplemented in our current implementation)
+
+_dvistate = enum.Enum('DviState', 'pre outer inpage post_post finale')
+
+# The marks on a page consist of text and boxes. A page also has dimensions.
+Page = namedtuple('Page', 'text boxes height width descent')
+Box = namedtuple('Box', 'x y height width')
+
+
+# Also a namedtuple, for backcompat.
+class Text(namedtuple('Text', 'x y font glyph width')):
+ """
+ A glyph in the dvi file.
+
+ The *x* and *y* attributes directly position the glyph. The *font*,
+ *glyph*, and *width* attributes are kept public for back-compatibility,
+ but users wanting to draw the glyph themselves are encouraged to instead
+ load the font specified by `font_path` at `font_size`, warp it with the
+ effects specified by `font_effects`, and load the glyph specified by
+ `glyph_name_or_index`.
+ """
+
+ def _get_pdftexmap_entry(self):
+ return PsfontsMap(find_tex_file("pdftex.map"))[self.font.texname]
+
+ @property
+ def font_path(self):
+ """The `~pathlib.Path` to the font for this glyph."""
+ psfont = self._get_pdftexmap_entry()
+ if psfont.filename is None:
+ raise ValueError("No usable font file found for {} ({}); "
+ "the font may lack a Type-1 version"
+ .format(psfont.psname.decode("ascii"),
+ psfont.texname.decode("ascii")))
+ return Path(psfont.filename)
+
+ @property
+ def font_size(self):
+ """The font size."""
+ return self.font.size
+
+ @property
+ def font_effects(self):
+ """
+ The "font effects" dict for this glyph.
+
+ This dict contains the values for this glyph of SlantFont and
+ ExtendFont (if any), read off :file:`pdftex.map`.
+ """
+ return self._get_pdftexmap_entry().effects
+
+ @property
+ def glyph_name_or_index(self):
+ """
+ Either the glyph name or the native charmap glyph index.
+
+ If :file:`pdftex.map` specifies an encoding for this glyph's font, that
+ is a mapping of glyph indices to Adobe glyph names; use it to convert
+ dvi indices to glyph names. Callers can then convert glyph names to
+ glyph indices (with FT_Get_Name_Index/get_name_index), and load the
+ glyph using FT_Load_Glyph/load_glyph.
+
+ If :file:`pdftex.map` specifies no encoding, the indices directly map
+ to the font's "native" charmap; glyphs should directly load using
+ FT_Load_Char/load_char after selecting the native charmap.
+ """
+ entry = self._get_pdftexmap_entry()
+ return (_parse_enc(entry.encoding)[self.glyph]
+ if entry.encoding is not None else self.glyph)
+
+
+# Opcode argument parsing
+#
+# Each of the following functions takes a Dvi object and delta,
+# which is the difference between the opcode and the minimum opcode
+# with the same meaning. Dvi opcodes often encode the number of
+# argument bytes in this delta.
+
+def _arg_raw(dvi, delta):
+ """Return *delta* without reading anything more from the dvi file."""
+ return delta
+
+
+def _arg(nbytes, signed, dvi, _):
+ """
+ Read *nbytes* bytes, returning the bytes interpreted as a signed integer
+ if *signed* is true, unsigned otherwise.
+ """
+ return dvi._arg(nbytes, signed)
+
+
+def _arg_slen(dvi, delta):
+ """
+ Read *delta* bytes, returning None if *delta* is zero, and the bytes
+ interpreted as a signed integer otherwise.
+ """
+ if delta == 0:
+ return None
+ return dvi._arg(delta, True)
+
+
+def _arg_slen1(dvi, delta):
+ """
+ Read *delta*+1 bytes, returning the bytes interpreted as signed.
+ """
+ return dvi._arg(delta + 1, True)
+
+
+def _arg_ulen1(dvi, delta):
+ """
+ Read *delta*+1 bytes, returning the bytes interpreted as unsigned.
+ """
+ return dvi._arg(delta + 1, False)
+
+
+def _arg_olen1(dvi, delta):
+ """
+ Read *delta*+1 bytes, returning the bytes interpreted as
+ unsigned integer for 0<=*delta*<3 and signed if *delta*==3.
+ """
+ return dvi._arg(delta + 1, delta == 3)
+
+
+_arg_mapping = dict(raw=_arg_raw,
+ u1=partial(_arg, 1, False),
+ u4=partial(_arg, 4, False),
+ s4=partial(_arg, 4, True),
+ slen=_arg_slen,
+ olen1=_arg_olen1,
+ slen1=_arg_slen1,
+ ulen1=_arg_ulen1)
+
+
+def _dispatch(table, min, max=None, state=None, args=('raw',)):
+ """
+ Decorator for dispatch by opcode. Sets the values in *table*
+ from *min* to *max* to this method, adds a check that the Dvi state
+ matches *state* if not None, reads arguments from the file according
+ to *args*.
+
+ Parameters
+ ----------
+ table : dict[int, callable]
+ The dispatch table to be filled in.
+
+ min, max : int
+ Range of opcodes that calls the registered function; *max* defaults to
+ *min*.
+
+ state : _dvistate, optional
+ State of the Dvi object in which these opcodes are allowed.
+
+ args : list[str], default: ['raw']
+ Sequence of argument specifications:
+
+ - 'raw': opcode minus minimum
+ - 'u1': read one unsigned byte
+ - 'u4': read four bytes, treat as an unsigned number
+ - 's4': read four bytes, treat as a signed number
+ - 'slen': read (opcode - minimum) bytes, treat as signed
+ - 'slen1': read (opcode - minimum + 1) bytes, treat as signed
+ - 'ulen1': read (opcode - minimum + 1) bytes, treat as unsigned
+ - 'olen1': read (opcode - minimum + 1) bytes, treat as unsigned
+ if under four bytes, signed if four bytes
+ """
+ def decorate(method):
+ get_args = [_arg_mapping[x] for x in args]
+
+ @wraps(method)
+ def wrapper(self, byte):
+ if state is not None and self.state != state:
+ raise ValueError("state precondition failed")
+ return method(self, *[f(self, byte-min) for f in get_args])
+ if max is None:
+ table[min] = wrapper
+ else:
+ for i in range(min, max+1):
+ assert table[i] is None
+ table[i] = wrapper
+ return wrapper
+ return decorate
+
+
+class Dvi:
+ """
+ A reader for a dvi ("device-independent") file, as produced by TeX.
+
+ The current implementation can only iterate through pages in order,
+ and does not even attempt to verify the postamble.
+
+ This class can be used as a context manager to close the underlying
+ file upon exit. Pages can be read via iteration. Here is an overly
+ simple way to extract text without trying to detect whitespace::
+
+ >>> with matplotlib.dviread.Dvi('input.dvi', 72) as dvi:
+ ... for page in dvi:
+ ... print(''.join(chr(t.glyph) for t in page.text))
+ """
+ # dispatch table
+ _dtable = [None] * 256
+ _dispatch = partial(_dispatch, _dtable)
+
+ def __init__(self, filename, dpi):
+ """
+ Read the data from the file named *filename* and convert
+ TeX's internal units to units of *dpi* per inch.
+ *dpi* only sets the units and does not limit the resolution.
+ Use None to return TeX's internal units.
+ """
+ _log.debug('Dvi: %s', filename)
+ self.file = open(filename, 'rb')
+ self.dpi = dpi
+ self.fonts = {}
+ self.state = _dvistate.pre
+
+ def __enter__(self):
+ """Context manager enter method, does nothing."""
+ return self
+
+ def __exit__(self, etype, evalue, etrace):
+ """
+ Context manager exit method, closes the underlying file if it is open.
+ """
+ self.close()
+
+ def __iter__(self):
+ """
+ Iterate through the pages of the file.
+
+ Yields
+ ------
+ Page
+ Details of all the text and box objects on the page.
+ The Page tuple contains lists of Text and Box tuples and
+ the page dimensions, and the Text and Box tuples contain
+ coordinates transformed into a standard Cartesian
+ coordinate system at the dpi value given when initializing.
+ The coordinates are floating point numbers, but otherwise
+ precision is not lost and coordinate values are not clipped to
+ integers.
+ """
+ while self._read():
+ yield self._output()
+
+ def close(self):
+ """Close the underlying file if it is open."""
+ if not self.file.closed:
+ self.file.close()
+
+ def _output(self):
+ """
+ Output the text and boxes belonging to the most recent page.
+ page = dvi._output()
+ """
+ minx, miny, maxx, maxy = np.inf, np.inf, -np.inf, -np.inf
+ maxy_pure = -np.inf
+ for elt in self.text + self.boxes:
+ if isinstance(elt, Box):
+ x, y, h, w = elt
+ e = 0 # zero depth
+ else: # glyph
+ x, y, font, g, w = elt
+ h, e = font._height_depth_of(g)
+ minx = min(minx, x)
+ miny = min(miny, y - h)
+ maxx = max(maxx, x + w)
+ maxy = max(maxy, y + e)
+ maxy_pure = max(maxy_pure, y)
+ if self._baseline_v is not None:
+ maxy_pure = self._baseline_v # This should normally be the case.
+ self._baseline_v = None
+
+ if not self.text and not self.boxes: # Avoid infs/nans from inf+/-inf.
+ return Page(text=[], boxes=[], width=0, height=0, descent=0)
+
+ if self.dpi is None:
+ # special case for ease of debugging: output raw dvi coordinates
+ return Page(text=self.text, boxes=self.boxes,
+ width=maxx-minx, height=maxy_pure-miny,
+ descent=maxy-maxy_pure)
+
+ # convert from TeX's "scaled points" to dpi units
+ d = self.dpi / (72.27 * 2**16)
+ descent = (maxy - maxy_pure) * d
+
+ text = [Text((x-minx)*d, (maxy-y)*d - descent, f, g, w*d)
+ for (x, y, f, g, w) in self.text]
+ boxes = [Box((x-minx)*d, (maxy-y)*d - descent, h*d, w*d)
+ for (x, y, h, w) in self.boxes]
+
+ return Page(text=text, boxes=boxes, width=(maxx-minx)*d,
+ height=(maxy_pure-miny)*d, descent=descent)
+
+ def _read(self):
+ """
+ Read one page from the file. Return True if successful,
+ False if there were no more pages.
+ """
+ # Pages appear to start with the sequence
+ # bop (begin of page)
+ # xxx comment
+ # # if using chemformula
+ # down
+ # push
+ # down
+ # # if using xcolor
+ # down
+ # push
+ # down (possibly multiple)
+ # push <= here, v is the baseline position.
+ # etc.
+ # (dviasm is useful to explore this structure.)
+ # Thus, we use the vertical position at the first time the stack depth
+ # reaches 3, while at least three "downs" have been executed (excluding
+ # those popped out (corresponding to the chemformula preamble)), as the
+ # baseline (the "down" count is necessary to handle xcolor).
+ down_stack = [0]
+ self._baseline_v = None
+ while True:
+ byte = self.file.read(1)[0]
+ self._dtable[byte](self, byte)
+ name = self._dtable[byte].__name__
+ if name == "_push":
+ down_stack.append(down_stack[-1])
+ elif name == "_pop":
+ down_stack.pop()
+ elif name == "_down":
+ down_stack[-1] += 1
+ if (self._baseline_v is None
+ and len(getattr(self, "stack", [])) == 3
+ and down_stack[-1] >= 4):
+ self._baseline_v = self.v
+ if byte == 140: # end of page
+ return True
+ if self.state is _dvistate.post_post: # end of file
+ self.close()
+ return False
+
+ def _arg(self, nbytes, signed=False):
+ """
+ Read and return an integer argument *nbytes* long.
+ Signedness is determined by the *signed* keyword.
+ """
+ buf = self.file.read(nbytes)
+ value = buf[0]
+ if signed and value >= 0x80:
+ value = value - 0x100
+ for b in buf[1:]:
+ value = 0x100*value + b
+ return value
+
+ @_dispatch(min=0, max=127, state=_dvistate.inpage)
+ def _set_char_immediate(self, char):
+ self._put_char_real(char)
+ self.h += self.fonts[self.f]._width_of(char)
+
+ @_dispatch(min=128, max=131, state=_dvistate.inpage, args=('olen1',))
+ def _set_char(self, char):
+ self._put_char_real(char)
+ self.h += self.fonts[self.f]._width_of(char)
+
+ @_dispatch(132, state=_dvistate.inpage, args=('s4', 's4'))
+ def _set_rule(self, a, b):
+ self._put_rule_real(a, b)
+ self.h += b
+
+ @_dispatch(min=133, max=136, state=_dvistate.inpage, args=('olen1',))
+ def _put_char(self, char):
+ self._put_char_real(char)
+
+ def _put_char_real(self, char):
+ font = self.fonts[self.f]
+ if font._vf is None:
+ self.text.append(Text(self.h, self.v, font, char,
+ font._width_of(char)))
+ else:
+ scale = font._scale
+ for x, y, f, g, w in font._vf[char].text:
+ newf = DviFont(scale=_mul2012(scale, f._scale),
+ tfm=f._tfm, texname=f.texname, vf=f._vf)
+ self.text.append(Text(self.h + _mul2012(x, scale),
+ self.v + _mul2012(y, scale),
+ newf, g, newf._width_of(g)))
+ self.boxes.extend([Box(self.h + _mul2012(x, scale),
+ self.v + _mul2012(y, scale),
+ _mul2012(a, scale), _mul2012(b, scale))
+ for x, y, a, b in font._vf[char].boxes])
+
+ @_dispatch(137, state=_dvistate.inpage, args=('s4', 's4'))
+ def _put_rule(self, a, b):
+ self._put_rule_real(a, b)
+
+ def _put_rule_real(self, a, b):
+ if a > 0 and b > 0:
+ self.boxes.append(Box(self.h, self.v, a, b))
+
+ @_dispatch(138)
+ def _nop(self, _):
+ pass
+
+ @_dispatch(139, state=_dvistate.outer, args=('s4',)*11)
+ def _bop(self, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, p):
+ self.state = _dvistate.inpage
+ self.h, self.v, self.w, self.x, self.y, self.z = 0, 0, 0, 0, 0, 0
+ self.stack = []
+ self.text = [] # list of Text objects
+ self.boxes = [] # list of Box objects
+
+ @_dispatch(140, state=_dvistate.inpage)
+ def _eop(self, _):
+ self.state = _dvistate.outer
+ del self.h, self.v, self.w, self.x, self.y, self.z, self.stack
+
+ @_dispatch(141, state=_dvistate.inpage)
+ def _push(self, _):
+ self.stack.append((self.h, self.v, self.w, self.x, self.y, self.z))
+
+ @_dispatch(142, state=_dvistate.inpage)
+ def _pop(self, _):
+ self.h, self.v, self.w, self.x, self.y, self.z = self.stack.pop()
+
+ @_dispatch(min=143, max=146, state=_dvistate.inpage, args=('slen1',))
+ def _right(self, b):
+ self.h += b
+
+ @_dispatch(min=147, max=151, state=_dvistate.inpage, args=('slen',))
+ def _right_w(self, new_w):
+ if new_w is not None:
+ self.w = new_w
+ self.h += self.w
+
+ @_dispatch(min=152, max=156, state=_dvistate.inpage, args=('slen',))
+ def _right_x(self, new_x):
+ if new_x is not None:
+ self.x = new_x
+ self.h += self.x
+
+ @_dispatch(min=157, max=160, state=_dvistate.inpage, args=('slen1',))
+ def _down(self, a):
+ self.v += a
+
+ @_dispatch(min=161, max=165, state=_dvistate.inpage, args=('slen',))
+ def _down_y(self, new_y):
+ if new_y is not None:
+ self.y = new_y
+ self.v += self.y
+
+ @_dispatch(min=166, max=170, state=_dvistate.inpage, args=('slen',))
+ def _down_z(self, new_z):
+ if new_z is not None:
+ self.z = new_z
+ self.v += self.z
+
+ @_dispatch(min=171, max=234, state=_dvistate.inpage)
+ def _fnt_num_immediate(self, k):
+ self.f = k
+
+ @_dispatch(min=235, max=238, state=_dvistate.inpage, args=('olen1',))
+ def _fnt_num(self, new_f):
+ self.f = new_f
+
+ @_dispatch(min=239, max=242, args=('ulen1',))
+ def _xxx(self, datalen):
+ special = self.file.read(datalen)
+ _log.debug(
+ 'Dvi._xxx: encountered special: %s',
+ ''.join([chr(ch) if 32 <= ch < 127 else '<%02x>' % ch
+ for ch in special]))
+
+ @_dispatch(min=243, max=246, args=('olen1', 'u4', 'u4', 'u4', 'u1', 'u1'))
+ def _fnt_def(self, k, c, s, d, a, l):
+ self._fnt_def_real(k, c, s, d, a, l)
+
+ def _fnt_def_real(self, k, c, s, d, a, l):
+ n = self.file.read(a + l)
+ fontname = n[-l:].decode('ascii')
+ tfm = _tfmfile(fontname)
+ if c != 0 and tfm.checksum != 0 and c != tfm.checksum:
+ raise ValueError('tfm checksum mismatch: %s' % n)
+ try:
+ vf = _vffile(fontname)
+ except FileNotFoundError:
+ vf = None
+ self.fonts[k] = DviFont(scale=s, tfm=tfm, texname=n, vf=vf)
+
+ @_dispatch(247, state=_dvistate.pre, args=('u1', 'u4', 'u4', 'u4', 'u1'))
+ def _pre(self, i, num, den, mag, k):
+ self.file.read(k) # comment in the dvi file
+ if i != 2:
+ raise ValueError("Unknown dvi format %d" % i)
+ if num != 25400000 or den != 7227 * 2**16:
+ raise ValueError("Nonstandard units in dvi file")
+ # meaning: TeX always uses those exact values, so it
+ # should be enough for us to support those
+ # (There are 72.27 pt to an inch so 7227 pt =
+ # 7227 * 2**16 sp to 100 in. The numerator is multiplied
+ # by 10^5 to get units of 10**-7 meters.)
+ if mag != 1000:
+ raise ValueError("Nonstandard magnification in dvi file")
+ # meaning: LaTeX seems to frown on setting \mag, so
+ # I think we can assume this is constant
+ self.state = _dvistate.outer
+
+ @_dispatch(248, state=_dvistate.outer)
+ def _post(self, _):
+ self.state = _dvistate.post_post
+ # TODO: actually read the postamble and finale?
+ # currently post_post just triggers closing the file
+
+ @_dispatch(249)
+ def _post_post(self, _):
+ raise NotImplementedError
+
+ @_dispatch(min=250, max=255)
+ def _malformed(self, offset):
+ raise ValueError(f"unknown command: byte {250 + offset}")
+
+
+class DviFont:
+ """
+ Encapsulation of a font that a DVI file can refer to.
+
+ This class holds a font's texname and size, supports comparison,
+ and knows the widths of glyphs in the same units as the AFM file.
+ There are also internal attributes (for use by dviread.py) that
+ are *not* used for comparison.
+
+ The size is in Adobe points (converted from TeX points).
+
+ Parameters
+ ----------
+ scale : float
+ Factor by which the font is scaled from its natural size.
+ tfm : Tfm
+ TeX font metrics for this font
+ texname : bytes
+ Name of the font as used internally by TeX and friends, as an ASCII
+ bytestring. This is usually very different from any external font
+ names; `PsfontsMap` can be used to find the external name of the font.
+ vf : Vf
+ A TeX "virtual font" file, or None if this font is not virtual.
+
+ Attributes
+ ----------
+ texname : bytes
+ size : float
+ Size of the font in Adobe points, converted from the slightly
+ smaller TeX points.
+ widths : list
+ Widths of glyphs in glyph-space units, typically 1/1000ths of
+ the point size.
+
+ """
+ __slots__ = ('texname', 'size', 'widths', '_scale', '_vf', '_tfm')
+
+ def __init__(self, scale, tfm, texname, vf):
+ _api.check_isinstance(bytes, texname=texname)
+ self._scale = scale
+ self._tfm = tfm
+ self.texname = texname
+ self._vf = vf
+ self.size = scale * (72.0 / (72.27 * 2**16))
+ try:
+ nchars = max(tfm.width) + 1
+ except ValueError:
+ nchars = 0
+ self.widths = [(1000*tfm.width.get(char, 0)) >> 20
+ for char in range(nchars)]
+
+ def __eq__(self, other):
+ return (type(self) is type(other)
+ and self.texname == other.texname and self.size == other.size)
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+ def __repr__(self):
+ return "<{}: {}>".format(type(self).__name__, self.texname)
+
+ def _width_of(self, char):
+ """Width of char in dvi units."""
+ width = self._tfm.width.get(char, None)
+ if width is not None:
+ return _mul2012(width, self._scale)
+ _log.debug('No width for char %d in font %s.', char, self.texname)
+ return 0
+
+ def _height_depth_of(self, char):
+ """Height and depth of char in dvi units."""
+ result = []
+ for metric, name in ((self._tfm.height, "height"),
+ (self._tfm.depth, "depth")):
+ value = metric.get(char, None)
+ if value is None:
+ _log.debug('No %s for char %d in font %s',
+ name, char, self.texname)
+ result.append(0)
+ else:
+ result.append(_mul2012(value, self._scale))
+ # cmsyXX (symbols font) glyph 0 ("minus") has a nonzero descent
+ # so that TeX aligns equations properly
+ # (https://tex.stackexchange.com/q/526103/)
+ # but we actually care about the rasterization depth to align
+ # the dvipng-generated images.
+ if re.match(br'^cmsy\d+$', self.texname) and char == 0:
+ result[-1] = 0
+ return result
+
+
+class Vf(Dvi):
+ r"""
+ A virtual font (\*.vf file) containing subroutines for dvi files.
+
+ Parameters
+ ----------
+ filename : str or path-like
+
+ Notes
+ -----
+ The virtual font format is a derivative of dvi:
+ http://mirrors.ctan.org/info/knuth/virtual-fonts
+ This class reuses some of the machinery of `Dvi`
+ but replaces the `_read` loop and dispatch mechanism.
+
+ Examples
+ --------
+ ::
+
+ vf = Vf(filename)
+ glyph = vf[code]
+ glyph.text, glyph.boxes, glyph.width
+ """
+
+ def __init__(self, filename):
+ super().__init__(filename, 0)
+ try:
+ self._first_font = None
+ self._chars = {}
+ self._read()
+ finally:
+ self.close()
+
+ def __getitem__(self, code):
+ return self._chars[code]
+
+ def _read(self):
+ """
+ Read one page from the file. Return True if successful,
+ False if there were no more pages.
+ """
+ packet_char, packet_ends = None, None
+ packet_len, packet_width = None, None
+ while True:
+ byte = self.file.read(1)[0]
+ # If we are in a packet, execute the dvi instructions
+ if self.state is _dvistate.inpage:
+ byte_at = self.file.tell()-1
+ if byte_at == packet_ends:
+ self._finalize_packet(packet_char, packet_width)
+ packet_len, packet_char, packet_width = None, None, None
+ # fall through to out-of-packet code
+ elif byte_at > packet_ends:
+ raise ValueError("Packet length mismatch in vf file")
+ else:
+ if byte in (139, 140) or byte >= 243:
+ raise ValueError(
+ "Inappropriate opcode %d in vf file" % byte)
+ Dvi._dtable[byte](self, byte)
+ continue
+
+ # We are outside a packet
+ if byte < 242: # a short packet (length given by byte)
+ packet_len = byte
+ packet_char, packet_width = self._arg(1), self._arg(3)
+ packet_ends = self._init_packet(byte)
+ self.state = _dvistate.inpage
+ elif byte == 242: # a long packet
+ packet_len, packet_char, packet_width = \
+ [self._arg(x) for x in (4, 4, 4)]
+ self._init_packet(packet_len)
+ elif 243 <= byte <= 246:
+ k = self._arg(byte - 242, byte == 246)
+ c, s, d, a, l = [self._arg(x) for x in (4, 4, 4, 1, 1)]
+ self._fnt_def_real(k, c, s, d, a, l)
+ if self._first_font is None:
+ self._first_font = k
+ elif byte == 247: # preamble
+ i, k = self._arg(1), self._arg(1)
+ x = self.file.read(k)
+ cs, ds = self._arg(4), self._arg(4)
+ self._pre(i, x, cs, ds)
+ elif byte == 248: # postamble (just some number of 248s)
+ break
+ else:
+ raise ValueError("Unknown vf opcode %d" % byte)
+
+ def _init_packet(self, pl):
+ if self.state != _dvistate.outer:
+ raise ValueError("Misplaced packet in vf file")
+ self.h, self.v, self.w, self.x, self.y, self.z = 0, 0, 0, 0, 0, 0
+ self.stack, self.text, self.boxes = [], [], []
+ self.f = self._first_font
+ return self.file.tell() + pl
+
+ def _finalize_packet(self, packet_char, packet_width):
+ self._chars[packet_char] = Page(
+ text=self.text, boxes=self.boxes, width=packet_width,
+ height=None, descent=None)
+ self.state = _dvistate.outer
+
+ def _pre(self, i, x, cs, ds):
+ if self.state is not _dvistate.pre:
+ raise ValueError("pre command in middle of vf file")
+ if i != 202:
+ raise ValueError("Unknown vf format %d" % i)
+ if len(x):
+ _log.debug('vf file comment: %s', x)
+ self.state = _dvistate.outer
+ # cs = checksum, ds = design size
+
+
+def _mul2012(num1, num2):
+ """Multiply two numbers in 20.12 fixed point format."""
+ # Separated into a function because >> has surprising precedence
+ return (num1*num2) >> 20
+
+
+class Tfm:
+ """
+ A TeX Font Metric file.
+
+ This implementation covers only the bare minimum needed by the Dvi class.
+
+ Parameters
+ ----------
+ filename : str or path-like
+
+ Attributes
+ ----------
+ checksum : int
+ Used for verifying against the dvi file.
+ design_size : int
+ Design size of the font (unknown units)
+ width, height, depth : dict
+ Dimensions of each character, need to be scaled by the factor
+ specified in the dvi file. These are dicts because indexing may
+ not start from 0.
+ """
+ __slots__ = ('checksum', 'design_size', 'width', 'height', 'depth')
+
+ def __init__(self, filename):
+ _log.debug('opening tfm file %s', filename)
+ with open(filename, 'rb') as file:
+ header1 = file.read(24)
+ lh, bc, ec, nw, nh, nd = struct.unpack('!6H', header1[2:14])
+ _log.debug('lh=%d, bc=%d, ec=%d, nw=%d, nh=%d, nd=%d',
+ lh, bc, ec, nw, nh, nd)
+ header2 = file.read(4*lh)
+ self.checksum, self.design_size = struct.unpack('!2I', header2[:8])
+ # there is also encoding information etc.
+ char_info = file.read(4*(ec-bc+1))
+ widths = struct.unpack(f'!{nw}i', file.read(4*nw))
+ heights = struct.unpack(f'!{nh}i', file.read(4*nh))
+ depths = struct.unpack(f'!{nd}i', file.read(4*nd))
+ self.width, self.height, self.depth = {}, {}, {}
+ for idx, char in enumerate(range(bc, ec+1)):
+ byte0 = char_info[4*idx]
+ byte1 = char_info[4*idx+1]
+ self.width[char] = widths[byte0]
+ self.height[char] = heights[byte1 >> 4]
+ self.depth[char] = depths[byte1 & 0xf]
+
+
+PsFont = namedtuple('PsFont', 'texname psname effects encoding filename')
+
+
+class PsfontsMap:
+ """
+ A psfonts.map formatted file, mapping TeX fonts to PS fonts.
+
+ Parameters
+ ----------
+ filename : str or path-like
+
+ Notes
+ -----
+ For historical reasons, TeX knows many Type-1 fonts by different
+ names than the outside world. (For one thing, the names have to
+ fit in eight characters.) Also, TeX's native fonts are not Type-1
+ but Metafont, which is nontrivial to convert to PostScript except
+ as a bitmap. While high-quality conversions to Type-1 format exist
+ and are shipped with modern TeX distributions, we need to know
+ which Type-1 fonts are the counterparts of which native fonts. For
+ these reasons a mapping is needed from internal font names to font
+ file names.
+
+ A texmf tree typically includes mapping files called e.g.
+ :file:`psfonts.map`, :file:`pdftex.map`, or :file:`dvipdfm.map`.
+ The file :file:`psfonts.map` is used by :program:`dvips`,
+ :file:`pdftex.map` by :program:`pdfTeX`, and :file:`dvipdfm.map`
+ by :program:`dvipdfm`. :file:`psfonts.map` might avoid embedding
+ the 35 PostScript fonts (i.e., have no filename for them, as in
+ the Times-Bold example above), while the pdf-related files perhaps
+ only avoid the "Base 14" pdf fonts. But the user may have
+ configured these files differently.
+
+ Examples
+ --------
+ >>> map = PsfontsMap(find_tex_file('pdftex.map'))
+ >>> entry = map[b'ptmbo8r']
+ >>> entry.texname
+ b'ptmbo8r'
+ >>> entry.psname
+ b'Times-Bold'
+ >>> entry.encoding
+ '/usr/local/texlive/2008/texmf-dist/fonts/enc/dvips/base/8r.enc'
+ >>> entry.effects
+ {'slant': 0.16700000000000001}
+ >>> entry.filename
+ """
+ __slots__ = ('_filename', '_unparsed', '_parsed')
+
+ # Create a filename -> PsfontsMap cache, so that calling
+ # `PsfontsMap(filename)` with the same filename a second time immediately
+ # returns the same object.
+ @lru_cache()
+ def __new__(cls, filename):
+ self = object.__new__(cls)
+ self._filename = os.fsdecode(filename)
+ # Some TeX distributions have enormous pdftex.map files which would
+ # take hundreds of milliseconds to parse, but it is easy enough to just
+ # store the unparsed lines (keyed by the first word, which is the
+ # texname) and parse them on-demand.
+ with open(filename, 'rb') as file:
+ self._unparsed = {}
+ for line in file:
+ tfmname = line.split(b' ', 1)[0]
+ self._unparsed.setdefault(tfmname, []).append(line)
+ self._parsed = {}
+ return self
+
+ def __getitem__(self, texname):
+ assert isinstance(texname, bytes)
+ if texname in self._unparsed:
+ for line in self._unparsed.pop(texname):
+ if self._parse_and_cache_line(line):
+ break
+ try:
+ return self._parsed[texname]
+ except KeyError:
+ raise LookupError(
+ f"An associated PostScript font (required by Matplotlib) "
+ f"could not be found for TeX font {texname.decode('ascii')!r} "
+ f"in {self._filename!r}; this problem can often be solved by "
+ f"installing a suitable PostScript font package in your TeX "
+ f"package manager") from None
+
+ def _parse_and_cache_line(self, line):
+ """
+ Parse a line in the font mapping file.
+
+ The format is (partially) documented at
+ http://mirrors.ctan.org/systems/doc/pdftex/manual/pdftex-a.pdf
+ https://tug.org/texinfohtml/dvips.html#psfonts_002emap
+ Each line can have the following fields:
+
+ - tfmname (first, only required field),
+ - psname (defaults to tfmname, must come immediately after tfmname if
+ present),
+ - fontflags (integer, must come immediately after psname if present,
+ ignored by us),
+ - special (SlantFont and ExtendFont, only field that is double-quoted),
+ - fontfile, encodingfile (optional, prefixed by <, <<, or <[; << always
+ precedes a font, <[ always precedes an encoding, < can precede either
+ but then an encoding file must have extension .enc; < and << also
+ request different font subsetting behaviors but we ignore that; < can
+ be separated from the filename by whitespace).
+
+ special, fontfile, and encodingfile can appear in any order.
+ """
+ # If the map file specifies multiple encodings for a font, we
+ # follow pdfTeX in choosing the last one specified. Such
+ # entries are probably mistakes but they have occurred.
+ # https://tex.stackexchange.com/q/10826/
+
+ if not line or line.startswith((b" ", b"%", b"*", b";", b"#")):
+ return
+ tfmname = basename = special = encodingfile = fontfile = None
+ is_subsetted = is_t1 = is_truetype = False
+ matches = re.finditer(br'"([^"]*)(?:"|$)|(\S+)', line)
+ for match in matches:
+ quoted, unquoted = match.groups()
+ if unquoted:
+ if unquoted.startswith(b"<<"): # font
+ fontfile = unquoted[2:]
+ elif unquoted.startswith(b"<["): # encoding
+ encodingfile = unquoted[2:]
+ elif unquoted.startswith(b"<"): # font or encoding
+ word = (
+ # foo
+ unquoted[1:]
+ # < by itself => read the next word
+ or next(filter(None, next(matches).groups())))
+ if word.endswith(b".enc"):
+ encodingfile = word
+ else:
+ fontfile = word
+ is_subsetted = True
+ elif tfmname is None:
+ tfmname = unquoted
+ elif basename is None:
+ basename = unquoted
+ elif quoted:
+ special = quoted
+ effects = {}
+ if special:
+ words = reversed(special.split())
+ for word in words:
+ if word == b"SlantFont":
+ effects["slant"] = float(next(words))
+ elif word == b"ExtendFont":
+ effects["extend"] = float(next(words))
+
+ # Verify some properties of the line that would cause it to be ignored
+ # otherwise.
+ if fontfile is not None:
+ if fontfile.endswith((b".ttf", b".ttc")):
+ is_truetype = True
+ elif not fontfile.endswith(b".otf"):
+ is_t1 = True
+ elif basename is not None:
+ is_t1 = True
+ if is_truetype and is_subsetted and encodingfile is None:
+ return
+ if not is_t1 and ("slant" in effects or "extend" in effects):
+ return
+ if abs(effects.get("slant", 0)) > 1:
+ return
+ if abs(effects.get("extend", 0)) > 2:
+ return
+
+ if basename is None:
+ basename = tfmname
+ if encodingfile is not None:
+ encodingfile = _find_tex_file(encodingfile)
+ if fontfile is not None:
+ fontfile = _find_tex_file(fontfile)
+ self._parsed[tfmname] = PsFont(
+ texname=tfmname, psname=basename, effects=effects,
+ encoding=encodingfile, filename=fontfile)
+ return True
+
+
+def _parse_enc(path):
+ r"""
+ Parse a \*.enc file referenced from a psfonts.map style file.
+
+ The format supported by this function is a tiny subset of PostScript.
+
+ Parameters
+ ----------
+ path : `os.PathLike`
+
+ Returns
+ -------
+ list
+ The nth entry of the list is the PostScript glyph name of the nth
+ glyph.
+ """
+ no_comments = re.sub("%.*", "", Path(path).read_text(encoding="ascii"))
+ array = re.search(r"(?s)\[(.*)\]", no_comments).group(1)
+ lines = [line for line in array.split() if line]
+ if all(line.startswith("/") for line in lines):
+ return [line[1:] for line in lines]
+ else:
+ raise ValueError(
+ "Failed to parse {} as Postscript encoding".format(path))
+
+
+class _LuatexKpsewhich:
+ @lru_cache() # A singleton.
+ def __new__(cls):
+ self = object.__new__(cls)
+ self._proc = self._new_proc()
+ return self
+
+ def _new_proc(self):
+ return subprocess.Popen(
+ ["luatex", "--luaonly",
+ str(cbook._get_data_path("kpsewhich.lua"))],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE)
+
+ def search(self, filename):
+ if self._proc.poll() is not None: # Dead, restart it.
+ self._proc = self._new_proc()
+ self._proc.stdin.write(os.fsencode(filename) + b"\n")
+ self._proc.stdin.flush()
+ out = self._proc.stdout.readline().rstrip()
+ return None if out == b"nil" else os.fsdecode(out)
+
+
+@lru_cache()
+def _find_tex_file(filename):
+ """
+ Find a file in the texmf tree using kpathsea_.
+
+ The kpathsea library, provided by most existing TeX distributions, both
+ on Unix-like systems and on Windows (MikTeX), is invoked via a long-lived
+ luatex process if luatex is installed, or via kpsewhich otherwise.
+
+ .. _kpathsea: https://www.tug.org/kpathsea/
+
+ Parameters
+ ----------
+ filename : str or path-like
+
+ Raises
+ ------
+ FileNotFoundError
+ If the file is not found.
+ """
+
+ # we expect these to always be ascii encoded, but use utf-8
+ # out of caution
+ if isinstance(filename, bytes):
+ filename = filename.decode('utf-8', errors='replace')
+
+ try:
+ lk = _LuatexKpsewhich()
+ except FileNotFoundError:
+ lk = None # Fallback to directly calling kpsewhich, as below.
+
+ if lk:
+ path = lk.search(filename)
+ else:
+ if os.name == 'nt':
+ # On Windows only, kpathsea can use utf-8 for cmd args and output.
+ # The `command_line_encoding` environment variable is set to force
+ # it to always use utf-8 encoding. See Matplotlib issue #11848.
+ kwargs = {'env': {**os.environ, 'command_line_encoding': 'utf-8'},
+ 'encoding': 'utf-8'}
+ else: # On POSIX, run through the equivalent of os.fsdecode().
+ kwargs = {'encoding': sys.getfilesystemencoding(),
+ 'errors': 'surrogateescape'}
+
+ try:
+ path = (cbook._check_and_log_subprocess(['kpsewhich', filename],
+ _log, **kwargs)
+ .rstrip('\n'))
+ except (FileNotFoundError, RuntimeError):
+ path = None
+
+ if path:
+ return path
+ else:
+ raise FileNotFoundError(
+ f"Matplotlib's TeX implementation searched for a file named "
+ f"{filename!r} in your texmf tree, but could not find it")
+
+
+# After the deprecation period elapses, delete this shim and rename
+# _find_tex_file to find_tex_file everywhere.
+def find_tex_file(filename):
+ try:
+ return _find_tex_file(filename)
+ except FileNotFoundError as exc:
+ _api.warn_deprecated(
+ "3.6", message=f"{exc.args[0]}; in the future, this will raise a "
+ f"FileNotFoundError.")
+ return ""
+
+
+find_tex_file.__doc__ = _find_tex_file.__doc__
+
+
+@lru_cache()
+def _fontfile(cls, suffix, texname):
+ return cls(_find_tex_file(texname + suffix))
+
+
+_tfmfile = partial(_fontfile, Tfm, ".tfm")
+_vffile = partial(_fontfile, Vf, ".vf")
+
+
+if __name__ == '__main__':
+ from argparse import ArgumentParser
+ import itertools
+
+ parser = ArgumentParser()
+ parser.add_argument("filename")
+ parser.add_argument("dpi", nargs="?", type=float, default=None)
+ args = parser.parse_args()
+ with Dvi(args.filename, args.dpi) as dvi:
+ fontmap = PsfontsMap(_find_tex_file('pdftex.map'))
+ for page in dvi:
+ print(f"=== new page === "
+ f"(w: {page.width}, h: {page.height}, d: {page.descent})")
+ for font, group in itertools.groupby(
+ page.text, lambda text: text.font):
+ print(f"font: {font.texname.decode('latin-1')!r}\t"
+ f"scale: {font._scale / 2 ** 20}")
+ print("x", "y", "glyph", "chr", "w", "(glyphs)", sep="\t")
+ for text in group:
+ print(text.x, text.y, text.glyph,
+ chr(text.glyph) if chr(text.glyph).isprintable()
+ else ".",
+ text.width, sep="\t")
+ if page.boxes:
+ print("x", "y", "h", "w", "", "(boxes)", sep="\t")
+ for box in page.boxes:
+ print(box.x, box.y, box.height, box.width, sep="\t")
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/figure.py b/omnilmm/lib/python3.10/site-packages/matplotlib/figure.py
new file mode 100644
index 0000000000000000000000000000000000000000..f79ec18b6d8df0db6ce5bfc22c4abc265b17e8c0
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/figure.py
@@ -0,0 +1,3629 @@
+"""
+`matplotlib.figure` implements the following classes:
+
+`Figure`
+ Top level `~matplotlib.artist.Artist`, which holds all plot elements.
+ Many methods are implemented in `FigureBase`.
+
+`SubFigure`
+ A logical figure inside a figure, usually added to a figure (or parent
+ `SubFigure`) with `Figure.add_subfigure` or `Figure.subfigures` methods
+ (provisional API v3.4).
+
+`SubplotParams`
+ Control the default spacing between subplots.
+
+Figures are typically created using pyplot methods `~.pyplot.figure`,
+`~.pyplot.subplots`, and `~.pyplot.subplot_mosaic`.
+
+.. plot::
+ :include-source:
+
+ fig, ax = plt.subplots(figsize=(2, 2), facecolor='lightskyblue',
+ layout='constrained')
+ fig.suptitle('Figure')
+ ax.set_title('Axes', loc='left', fontstyle='oblique', fontsize='medium')
+
+Some situations call for directly instantiating a `~.figure.Figure` class,
+usually inside an application of some sort (see :ref:`user_interfaces` for a
+list of examples) . More information about Figures can be found at
+:ref:`figure_explanation`.
+
+"""
+
+from contextlib import ExitStack
+import inspect
+import itertools
+import logging
+from numbers import Integral
+
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib import _blocking_input, backend_bases, _docstring, projections
+from matplotlib.artist import (
+ Artist, allow_rasterization, _finalize_rasterization)
+from matplotlib.backend_bases import (
+ DrawEvent, FigureCanvasBase, NonGuiException, MouseButton, _get_renderer)
+import matplotlib._api as _api
+import matplotlib.cbook as cbook
+import matplotlib.colorbar as cbar
+import matplotlib.image as mimage
+
+from matplotlib.axes import Axes
+from matplotlib.gridspec import GridSpec
+from matplotlib.layout_engine import (
+ ConstrainedLayoutEngine, TightLayoutEngine, LayoutEngine,
+ PlaceHolderLayoutEngine
+)
+import matplotlib.legend as mlegend
+from matplotlib.patches import Rectangle
+from matplotlib.text import Text
+from matplotlib.transforms import (Affine2D, Bbox, BboxTransformTo,
+ TransformedBbox)
+
+_log = logging.getLogger(__name__)
+
+
+def _stale_figure_callback(self, val):
+ if self.figure:
+ self.figure.stale = val
+
+
+class _AxesStack:
+ """
+ Helper class to track axes in a figure.
+
+ Axes are tracked both in the order in which they have been added
+ (``self._axes`` insertion/iteration order) and in the separate "gca" stack
+ (which is the index to which they map in the ``self._axes`` dict).
+ """
+
+ def __init__(self):
+ self._axes = {} # Mapping of axes to "gca" order.
+ self._counter = itertools.count()
+
+ def as_list(self):
+ """List the axes that have been added to the figure."""
+ return [*self._axes] # This relies on dict preserving order.
+
+ def remove(self, a):
+ """Remove the axes from the stack."""
+ self._axes.pop(a)
+
+ def bubble(self, a):
+ """Move an axes, which must already exist in the stack, to the top."""
+ if a not in self._axes:
+ raise ValueError("Axes has not been added yet")
+ self._axes[a] = next(self._counter)
+
+ def add(self, a):
+ """Add an axes to the stack, ignoring it if already present."""
+ if a not in self._axes:
+ self._axes[a] = next(self._counter)
+
+ def current(self):
+ """Return the active axes, or None if the stack is empty."""
+ return max(self._axes, key=self._axes.__getitem__, default=None)
+
+ def __getstate__(self):
+ return {
+ **vars(self),
+ "_counter": max(self._axes.values(), default=0)
+ }
+
+ def __setstate__(self, state):
+ next_counter = state.pop('_counter')
+ vars(self).update(state)
+ self._counter = itertools.count(next_counter)
+
+
+class SubplotParams:
+ """
+ A class to hold the parameters for a subplot.
+ """
+
+ def __init__(self, left=None, bottom=None, right=None, top=None,
+ wspace=None, hspace=None):
+ """
+ Defaults are given by :rc:`figure.subplot.[name]`.
+
+ Parameters
+ ----------
+ left : float
+ The position of the left edge of the subplots,
+ as a fraction of the figure width.
+ right : float
+ The position of the right edge of the subplots,
+ as a fraction of the figure width.
+ bottom : float
+ The position of the bottom edge of the subplots,
+ as a fraction of the figure height.
+ top : float
+ The position of the top edge of the subplots,
+ as a fraction of the figure height.
+ wspace : float
+ The width of the padding between subplots,
+ as a fraction of the average Axes width.
+ hspace : float
+ The height of the padding between subplots,
+ as a fraction of the average Axes height.
+ """
+ for key in ["left", "bottom", "right", "top", "wspace", "hspace"]:
+ setattr(self, key, mpl.rcParams[f"figure.subplot.{key}"])
+ self.update(left, bottom, right, top, wspace, hspace)
+
+ def update(self, left=None, bottom=None, right=None, top=None,
+ wspace=None, hspace=None):
+ """
+ Update the dimensions of the passed parameters. *None* means unchanged.
+ """
+ if ((left if left is not None else self.left)
+ >= (right if right is not None else self.right)):
+ raise ValueError('left cannot be >= right')
+ if ((bottom if bottom is not None else self.bottom)
+ >= (top if top is not None else self.top)):
+ raise ValueError('bottom cannot be >= top')
+ if left is not None:
+ self.left = left
+ if right is not None:
+ self.right = right
+ if bottom is not None:
+ self.bottom = bottom
+ if top is not None:
+ self.top = top
+ if wspace is not None:
+ self.wspace = wspace
+ if hspace is not None:
+ self.hspace = hspace
+
+
+class FigureBase(Artist):
+ """
+ Base class for `.Figure` and `.SubFigure` containing the methods that add
+ artists to the figure or subfigure, create Axes, etc.
+ """
+ def __init__(self, **kwargs):
+ super().__init__()
+ # remove the non-figure artist _axes property
+ # as it makes no sense for a figure to be _in_ an Axes
+ # this is used by the property methods in the artist base class
+ # which are over-ridden in this class
+ del self._axes
+
+ self._suptitle = None
+ self._supxlabel = None
+ self._supylabel = None
+
+ # groupers to keep track of x and y labels we want to align.
+ # see self.align_xlabels and self.align_ylabels and
+ # axis._get_tick_boxes_siblings
+ self._align_label_groups = {"x": cbook.Grouper(), "y": cbook.Grouper()}
+
+ self.figure = self
+ self._localaxes = [] # track all axes
+ self.artists = []
+ self.lines = []
+ self.patches = []
+ self.texts = []
+ self.images = []
+ self.legends = []
+ self.subfigs = []
+ self.stale = True
+ self.suppressComposite = None
+ self.set(**kwargs)
+
+ def _get_draw_artists(self, renderer):
+ """Also runs apply_aspect"""
+ artists = self.get_children()
+ for sfig in self.subfigs:
+ artists.remove(sfig)
+ childa = sfig.get_children()
+ for child in childa:
+ if child in artists:
+ artists.remove(child)
+
+ artists.remove(self.patch)
+ artists = sorted(
+ (artist for artist in artists if not artist.get_animated()),
+ key=lambda artist: artist.get_zorder())
+ for ax in self._localaxes:
+ locator = ax.get_axes_locator()
+ ax.apply_aspect(locator(ax, renderer) if locator else None)
+
+ for child in ax.get_children():
+ if hasattr(child, 'apply_aspect'):
+ locator = child.get_axes_locator()
+ child.apply_aspect(
+ locator(child, renderer) if locator else None)
+ return artists
+
+ def autofmt_xdate(
+ self, bottom=0.2, rotation=30, ha='right', which='major'):
+ """
+ Date ticklabels often overlap, so it is useful to rotate them
+ and right align them. Also, a common use case is a number of
+ subplots with shared x-axis where the x-axis is date data. The
+ ticklabels are often long, and it helps to rotate them on the
+ bottom subplot and turn them off on other subplots, as well as
+ turn off xlabels.
+
+ Parameters
+ ----------
+ bottom : float, default: 0.2
+ The bottom of the subplots for `subplots_adjust`.
+ rotation : float, default: 30 degrees
+ The rotation angle of the xtick labels in degrees.
+ ha : {'left', 'center', 'right'}, default: 'right'
+ The horizontal alignment of the xticklabels.
+ which : {'major', 'minor', 'both'}, default: 'major'
+ Selects which ticklabels to rotate.
+ """
+ _api.check_in_list(['major', 'minor', 'both'], which=which)
+ allsubplots = all(ax.get_subplotspec() for ax in self.axes)
+ if len(self.axes) == 1:
+ for label in self.axes[0].get_xticklabels(which=which):
+ label.set_ha(ha)
+ label.set_rotation(rotation)
+ else:
+ if allsubplots:
+ for ax in self.get_axes():
+ if ax.get_subplotspec().is_last_row():
+ for label in ax.get_xticklabels(which=which):
+ label.set_ha(ha)
+ label.set_rotation(rotation)
+ else:
+ for label in ax.get_xticklabels(which=which):
+ label.set_visible(False)
+ ax.set_xlabel('')
+
+ if allsubplots:
+ self.subplots_adjust(bottom=bottom)
+ self.stale = True
+
+ def get_children(self):
+ """Get a list of artists contained in the figure."""
+ return [self.patch,
+ *self.artists,
+ *self._localaxes,
+ *self.lines,
+ *self.patches,
+ *self.texts,
+ *self.images,
+ *self.legends,
+ *self.subfigs]
+
+ def contains(self, mouseevent):
+ """
+ Test whether the mouse event occurred on the figure.
+
+ Returns
+ -------
+ bool, {}
+ """
+ inside, info = self._default_contains(mouseevent, figure=self)
+ if inside is not None:
+ return inside, info
+ inside = self.bbox.contains(mouseevent.x, mouseevent.y)
+ return inside, {}
+
+ @_api.delete_parameter("3.6", "args")
+ @_api.delete_parameter("3.6", "kwargs")
+ def get_window_extent(self, renderer=None, *args, **kwargs):
+ # docstring inherited
+ return self.bbox
+
+ def _suplabels(self, t, info, **kwargs):
+ """
+ Add a centered %(name)s to the figure.
+
+ Parameters
+ ----------
+ t : str
+ The %(name)s text.
+ x : float, default: %(x0)s
+ The x location of the text in figure coordinates.
+ y : float, default: %(y0)s
+ The y location of the text in figure coordinates.
+ horizontalalignment, ha : {'center', 'left', 'right'}, default: %(ha)s
+ The horizontal alignment of the text relative to (*x*, *y*).
+ verticalalignment, va : {'top', 'center', 'bottom', 'baseline'}, \
+default: %(va)s
+ The vertical alignment of the text relative to (*x*, *y*).
+ fontsize, size : default: :rc:`figure.%(rc)ssize`
+ The font size of the text. See `.Text.set_size` for possible
+ values.
+ fontweight, weight : default: :rc:`figure.%(rc)sweight`
+ The font weight of the text. See `.Text.set_weight` for possible
+ values.
+
+ Returns
+ -------
+ text
+ The `.Text` instance of the %(name)s.
+
+ Other Parameters
+ ----------------
+ fontproperties : None or dict, optional
+ A dict of font properties. If *fontproperties* is given the
+ default values for font size and weight are taken from the
+ `.FontProperties` defaults. :rc:`figure.%(rc)ssize` and
+ :rc:`figure.%(rc)sweight` are ignored in this case.
+
+ **kwargs
+ Additional kwargs are `matplotlib.text.Text` properties.
+ """
+
+ suplab = getattr(self, info['name'])
+
+ x = kwargs.pop('x', None)
+ y = kwargs.pop('y', None)
+ if info['name'] in ['_supxlabel', '_suptitle']:
+ autopos = y is None
+ elif info['name'] == '_supylabel':
+ autopos = x is None
+ if x is None:
+ x = info['x0']
+ if y is None:
+ y = info['y0']
+
+ if 'horizontalalignment' not in kwargs and 'ha' not in kwargs:
+ kwargs['horizontalalignment'] = info['ha']
+ if 'verticalalignment' not in kwargs and 'va' not in kwargs:
+ kwargs['verticalalignment'] = info['va']
+ if 'rotation' not in kwargs:
+ kwargs['rotation'] = info['rotation']
+
+ if 'fontproperties' not in kwargs:
+ if 'fontsize' not in kwargs and 'size' not in kwargs:
+ kwargs['size'] = mpl.rcParams[info['size']]
+ if 'fontweight' not in kwargs and 'weight' not in kwargs:
+ kwargs['weight'] = mpl.rcParams[info['weight']]
+
+ sup = self.text(x, y, t, **kwargs)
+ if suplab is not None:
+ suplab.set_text(t)
+ suplab.set_position((x, y))
+ suplab.update_from(sup)
+ sup.remove()
+ else:
+ suplab = sup
+ suplab._autopos = autopos
+ setattr(self, info['name'], suplab)
+ self.stale = True
+ return suplab
+
+ @_docstring.Substitution(x0=0.5, y0=0.98, name='suptitle', ha='center',
+ va='top', rc='title')
+ @_docstring.copy(_suplabels)
+ def suptitle(self, t, **kwargs):
+ # docstring from _suplabels...
+ info = {'name': '_suptitle', 'x0': 0.5, 'y0': 0.98,
+ 'ha': 'center', 'va': 'top', 'rotation': 0,
+ 'size': 'figure.titlesize', 'weight': 'figure.titleweight'}
+ return self._suplabels(t, info, **kwargs)
+
+ @_docstring.Substitution(x0=0.5, y0=0.01, name='supxlabel', ha='center',
+ va='bottom', rc='label')
+ @_docstring.copy(_suplabels)
+ def supxlabel(self, t, **kwargs):
+ # docstring from _suplabels...
+ info = {'name': '_supxlabel', 'x0': 0.5, 'y0': 0.01,
+ 'ha': 'center', 'va': 'bottom', 'rotation': 0,
+ 'size': 'figure.labelsize', 'weight': 'figure.labelweight'}
+ return self._suplabels(t, info, **kwargs)
+
+ @_docstring.Substitution(x0=0.02, y0=0.5, name='supylabel', ha='left',
+ va='center', rc='label')
+ @_docstring.copy(_suplabels)
+ def supylabel(self, t, **kwargs):
+ # docstring from _suplabels...
+ info = {'name': '_supylabel', 'x0': 0.02, 'y0': 0.5,
+ 'ha': 'left', 'va': 'center', 'rotation': 'vertical',
+ 'rotation_mode': 'anchor', 'size': 'figure.labelsize',
+ 'weight': 'figure.labelweight'}
+ return self._suplabels(t, info, **kwargs)
+
+ def get_edgecolor(self):
+ """Get the edge color of the Figure rectangle."""
+ return self.patch.get_edgecolor()
+
+ def get_facecolor(self):
+ """Get the face color of the Figure rectangle."""
+ return self.patch.get_facecolor()
+
+ def get_frameon(self):
+ """
+ Return the figure's background patch visibility, i.e.
+ whether the figure background will be drawn. Equivalent to
+ ``Figure.patch.get_visible()``.
+ """
+ return self.patch.get_visible()
+
+ def set_linewidth(self, linewidth):
+ """
+ Set the line width of the Figure rectangle.
+
+ Parameters
+ ----------
+ linewidth : number
+ """
+ self.patch.set_linewidth(linewidth)
+
+ def get_linewidth(self):
+ """
+ Get the line width of the Figure rectangle.
+ """
+ return self.patch.get_linewidth()
+
+ def set_edgecolor(self, color):
+ """
+ Set the edge color of the Figure rectangle.
+
+ Parameters
+ ----------
+ color : color
+ """
+ self.patch.set_edgecolor(color)
+
+ def set_facecolor(self, color):
+ """
+ Set the face color of the Figure rectangle.
+
+ Parameters
+ ----------
+ color : color
+ """
+ self.patch.set_facecolor(color)
+
+ def set_frameon(self, b):
+ """
+ Set the figure's background patch visibility, i.e.
+ whether the figure background will be drawn. Equivalent to
+ ``Figure.patch.set_visible()``.
+
+ Parameters
+ ----------
+ b : bool
+ """
+ self.patch.set_visible(b)
+ self.stale = True
+
+ frameon = property(get_frameon, set_frameon)
+
+ def add_artist(self, artist, clip=False):
+ """
+ Add an `.Artist` to the figure.
+
+ Usually artists are added to `~.axes.Axes` objects using
+ `.Axes.add_artist`; this method can be used in the rare cases where
+ one needs to add artists directly to the figure instead.
+
+ Parameters
+ ----------
+ artist : `~matplotlib.artist.Artist`
+ The artist to add to the figure. If the added artist has no
+ transform previously set, its transform will be set to
+ ``figure.transSubfigure``.
+ clip : bool, default: False
+ Whether the added artist should be clipped by the figure patch.
+
+ Returns
+ -------
+ `~matplotlib.artist.Artist`
+ The added artist.
+ """
+ artist.set_figure(self)
+ self.artists.append(artist)
+ artist._remove_method = self.artists.remove
+
+ if not artist.is_transform_set():
+ artist.set_transform(self.transSubfigure)
+
+ if clip:
+ artist.set_clip_path(self.patch)
+
+ self.stale = True
+ return artist
+
+ @_docstring.dedent_interpd
+ def add_axes(self, *args, **kwargs):
+ """
+ Add an `~.axes.Axes` to the figure.
+
+ Call signatures::
+
+ add_axes(rect, projection=None, polar=False, **kwargs)
+ add_axes(ax)
+
+ Parameters
+ ----------
+ rect : tuple (left, bottom, width, height)
+ The dimensions (left, bottom, width, height) of the new
+ `~.axes.Axes`. All quantities are in fractions of figure width and
+ height.
+
+ projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
+'polar', 'rectilinear', str}, optional
+ The projection type of the `~.axes.Axes`. *str* is the name of
+ a custom projection, see `~matplotlib.projections`. The default
+ None results in a 'rectilinear' projection.
+
+ polar : bool, default: False
+ If True, equivalent to projection='polar'.
+
+ axes_class : subclass type of `~.axes.Axes`, optional
+ The `.axes.Axes` subclass that is instantiated. This parameter
+ is incompatible with *projection* and *polar*. See
+ :ref:`axisartist_users-guide-index` for examples.
+
+ sharex, sharey : `~matplotlib.axes.Axes`, optional
+ Share the x or y `~matplotlib.axis` with sharex and/or sharey.
+ The axis will have the same limits, ticks, and scale as the axis
+ of the shared axes.
+
+ label : str
+ A label for the returned Axes.
+
+ Returns
+ -------
+ `~.axes.Axes`, or a subclass of `~.axes.Axes`
+ The returned axes class depends on the projection used. It is
+ `~.axes.Axes` if rectilinear projection is used and
+ `.projections.polar.PolarAxes` if polar projection is used.
+
+ Other Parameters
+ ----------------
+ **kwargs
+ This method also takes the keyword arguments for
+ the returned Axes class. The keyword arguments for the
+ rectilinear Axes class `~.axes.Axes` can be found in
+ the following table but there might also be other keyword
+ arguments if another projection is used, see the actual Axes
+ class.
+
+ %(Axes:kwdoc)s
+
+ Notes
+ -----
+ In rare circumstances, `.add_axes` may be called with a single
+ argument, an Axes instance already created in the present figure but
+ not in the figure's list of Axes.
+
+ See Also
+ --------
+ .Figure.add_subplot
+ .pyplot.subplot
+ .pyplot.axes
+ .Figure.subplots
+ .pyplot.subplots
+
+ Examples
+ --------
+ Some simple examples::
+
+ rect = l, b, w, h
+ fig = plt.figure()
+ fig.add_axes(rect)
+ fig.add_axes(rect, frameon=False, facecolor='g')
+ fig.add_axes(rect, polar=True)
+ ax = fig.add_axes(rect, projection='polar')
+ fig.delaxes(ax)
+ fig.add_axes(ax)
+ """
+
+ if not len(args) and 'rect' not in kwargs:
+ raise TypeError(
+ "add_axes() missing 1 required positional argument: 'rect'")
+ elif 'rect' in kwargs:
+ if len(args):
+ raise TypeError(
+ "add_axes() got multiple values for argument 'rect'")
+ args = (kwargs.pop('rect'), )
+
+ if isinstance(args[0], Axes):
+ a = args[0]
+ key = a._projection_init
+ if a.get_figure() is not self:
+ raise ValueError(
+ "The Axes must have been created in the present figure")
+ else:
+ rect = args[0]
+ if not np.isfinite(rect).all():
+ raise ValueError('all entries in rect must be finite '
+ 'not {}'.format(rect))
+ projection_class, pkw = self._process_projection_requirements(
+ *args, **kwargs)
+
+ # create the new axes using the axes class given
+ a = projection_class(self, rect, **pkw)
+ key = (projection_class, pkw)
+ return self._add_axes_internal(a, key)
+
+ @_docstring.dedent_interpd
+ def add_subplot(self, *args, **kwargs):
+ """
+ Add an `~.axes.Axes` to the figure as part of a subplot arrangement.
+
+ Call signatures::
+
+ add_subplot(nrows, ncols, index, **kwargs)
+ add_subplot(pos, **kwargs)
+ add_subplot(ax)
+ add_subplot()
+
+ Parameters
+ ----------
+ *args : int, (int, int, *index*), or `.SubplotSpec`, default: (1, 1, 1)
+ The position of the subplot described by one of
+
+ - Three integers (*nrows*, *ncols*, *index*). The subplot will
+ take the *index* position on a grid with *nrows* rows and
+ *ncols* columns. *index* starts at 1 in the upper left corner
+ and increases to the right. *index* can also be a two-tuple
+ specifying the (*first*, *last*) indices (1-based, and including
+ *last*) of the subplot, e.g., ``fig.add_subplot(3, 1, (1, 2))``
+ makes a subplot that spans the upper 2/3 of the figure.
+ - A 3-digit integer. The digits are interpreted as if given
+ separately as three single-digit integers, i.e.
+ ``fig.add_subplot(235)`` is the same as
+ ``fig.add_subplot(2, 3, 5)``. Note that this can only be used
+ if there are no more than 9 subplots.
+ - A `.SubplotSpec`.
+
+ In rare circumstances, `.add_subplot` may be called with a single
+ argument, a subplot Axes instance already created in the
+ present figure but not in the figure's list of Axes.
+
+ projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
+'polar', 'rectilinear', str}, optional
+ The projection type of the subplot (`~.axes.Axes`). *str* is the
+ name of a custom projection, see `~matplotlib.projections`. The
+ default None results in a 'rectilinear' projection.
+
+ polar : bool, default: False
+ If True, equivalent to projection='polar'.
+
+ axes_class : subclass type of `~.axes.Axes`, optional
+ The `.axes.Axes` subclass that is instantiated. This parameter
+ is incompatible with *projection* and *polar*. See
+ :ref:`axisartist_users-guide-index` for examples.
+
+ sharex, sharey : `~matplotlib.axes.Axes`, optional
+ Share the x or y `~matplotlib.axis` with sharex and/or sharey.
+ The axis will have the same limits, ticks, and scale as the axis
+ of the shared axes.
+
+ label : str
+ A label for the returned Axes.
+
+ Returns
+ -------
+ `~.axes.Axes`
+
+ The Axes of the subplot. The returned Axes can actually be an
+ instance of a subclass, such as `.projections.polar.PolarAxes` for
+ polar projections.
+
+ Other Parameters
+ ----------------
+ **kwargs
+ This method also takes the keyword arguments for the returned Axes
+ base class; except for the *figure* argument. The keyword arguments
+ for the rectilinear base class `~.axes.Axes` can be found in
+ the following table but there might also be other keyword
+ arguments if another projection is used.
+
+ %(Axes:kwdoc)s
+
+ See Also
+ --------
+ .Figure.add_axes
+ .pyplot.subplot
+ .pyplot.axes
+ .Figure.subplots
+ .pyplot.subplots
+
+ Examples
+ --------
+ ::
+
+ fig = plt.figure()
+
+ fig.add_subplot(231)
+ ax1 = fig.add_subplot(2, 3, 1) # equivalent but more general
+
+ fig.add_subplot(232, frameon=False) # subplot with no frame
+ fig.add_subplot(233, projection='polar') # polar subplot
+ fig.add_subplot(234, sharex=ax1) # subplot sharing x-axis with ax1
+ fig.add_subplot(235, facecolor="red") # red subplot
+
+ ax1.remove() # delete ax1 from the figure
+ fig.add_subplot(ax1) # add ax1 back to the figure
+ """
+ if 'figure' in kwargs:
+ # Axes itself allows for a 'figure' kwarg, but since we want to
+ # bind the created Axes to self, it is not allowed here.
+ raise _api.kwarg_error("add_subplot", "figure")
+
+ if (len(args) == 1
+ and isinstance(args[0], mpl.axes._base._AxesBase)
+ and args[0].get_subplotspec()):
+ ax = args[0]
+ key = ax._projection_init
+ if ax.get_figure() is not self:
+ raise ValueError("The Axes must have been created in "
+ "the present figure")
+ else:
+ if not args:
+ args = (1, 1, 1)
+ # Normalize correct ijk values to (i, j, k) here so that
+ # add_subplot(211) == add_subplot(2, 1, 1). Invalid values will
+ # trigger errors later (via SubplotSpec._from_subplot_args).
+ if (len(args) == 1 and isinstance(args[0], Integral)
+ and 100 <= args[0] <= 999):
+ args = tuple(map(int, str(args[0])))
+ projection_class, pkw = self._process_projection_requirements(
+ *args, **kwargs)
+ ax = projection_class(self, *args, **pkw)
+ key = (projection_class, pkw)
+ return self._add_axes_internal(ax, key)
+
+ def _add_axes_internal(self, ax, key):
+ """Private helper for `add_axes` and `add_subplot`."""
+ self._axstack.add(ax)
+ if ax not in self._localaxes:
+ self._localaxes.append(ax)
+ self.sca(ax)
+ ax._remove_method = self.delaxes
+ # this is to support plt.subplot's re-selection logic
+ ax._projection_init = key
+ self.stale = True
+ ax.stale_callback = _stale_figure_callback
+ return ax
+
+ def subplots(self, nrows=1, ncols=1, *, sharex=False, sharey=False,
+ squeeze=True, width_ratios=None, height_ratios=None,
+ subplot_kw=None, gridspec_kw=None):
+ """
+ Add a set of subplots to this figure.
+
+ This utility wrapper makes it convenient to create common layouts of
+ subplots in a single call.
+
+ Parameters
+ ----------
+ nrows, ncols : int, default: 1
+ Number of rows/columns of the subplot grid.
+
+ sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
+ Controls sharing of x-axis (*sharex*) or y-axis (*sharey*):
+
+ - True or 'all': x- or y-axis will be shared among all subplots.
+ - False or 'none': each subplot x- or y-axis will be independent.
+ - 'row': each subplot row will share an x- or y-axis.
+ - 'col': each subplot column will share an x- or y-axis.
+
+ When subplots have a shared x-axis along a column, only the x tick
+ labels of the bottom subplot are created. Similarly, when subplots
+ have a shared y-axis along a row, only the y tick labels of the
+ first column subplot are created. To later turn other subplots'
+ ticklabels on, use `~matplotlib.axes.Axes.tick_params`.
+
+ When subplots have a shared axis that has units, calling
+ `.Axis.set_units` will update each axis with the new units.
+
+ squeeze : bool, default: True
+ - If True, extra dimensions are squeezed out from the returned
+ array of Axes:
+
+ - if only one subplot is constructed (nrows=ncols=1), the
+ resulting single Axes object is returned as a scalar.
+ - for Nx1 or 1xM subplots, the returned object is a 1D numpy
+ object array of Axes objects.
+ - for NxM, subplots with N>1 and M>1 are returned as a 2D array.
+
+ - If False, no squeezing at all is done: the returned Axes object
+ is always a 2D array containing Axes instances, even if it ends
+ up being 1x1.
+
+ width_ratios : array-like of length *ncols*, optional
+ Defines the relative widths of the columns. Each column gets a
+ relative width of ``width_ratios[i] / sum(width_ratios)``.
+ If not given, all columns will have the same width. Equivalent
+ to ``gridspec_kw={'width_ratios': [...]}``.
+
+ height_ratios : array-like of length *nrows*, optional
+ Defines the relative heights of the rows. Each row gets a
+ relative height of ``height_ratios[i] / sum(height_ratios)``.
+ If not given, all rows will have the same height. Equivalent
+ to ``gridspec_kw={'height_ratios': [...]}``.
+
+ subplot_kw : dict, optional
+ Dict with keywords passed to the `.Figure.add_subplot` call used to
+ create each subplot.
+
+ gridspec_kw : dict, optional
+ Dict with keywords passed to the
+ `~matplotlib.gridspec.GridSpec` constructor used to create
+ the grid the subplots are placed on.
+
+ Returns
+ -------
+ `~.axes.Axes` or array of Axes
+ Either a single `~matplotlib.axes.Axes` object or an array of Axes
+ objects if more than one subplot was created. The dimensions of the
+ resulting array can be controlled with the *squeeze* keyword, see
+ above.
+
+ See Also
+ --------
+ .pyplot.subplots
+ .Figure.add_subplot
+ .pyplot.subplot
+
+ Examples
+ --------
+ ::
+
+ # First create some toy data:
+ x = np.linspace(0, 2*np.pi, 400)
+ y = np.sin(x**2)
+
+ # Create a figure
+ plt.figure()
+
+ # Create a subplot
+ ax = fig.subplots()
+ ax.plot(x, y)
+ ax.set_title('Simple plot')
+
+ # Create two subplots and unpack the output array immediately
+ ax1, ax2 = fig.subplots(1, 2, sharey=True)
+ ax1.plot(x, y)
+ ax1.set_title('Sharing Y axis')
+ ax2.scatter(x, y)
+
+ # Create four polar Axes and access them through the returned array
+ axes = fig.subplots(2, 2, subplot_kw=dict(projection='polar'))
+ axes[0, 0].plot(x, y)
+ axes[1, 1].scatter(x, y)
+
+ # Share an X-axis with each column of subplots
+ fig.subplots(2, 2, sharex='col')
+
+ # Share a Y-axis with each row of subplots
+ fig.subplots(2, 2, sharey='row')
+
+ # Share both X- and Y-axes with all subplots
+ fig.subplots(2, 2, sharex='all', sharey='all')
+
+ # Note that this is the same as
+ fig.subplots(2, 2, sharex=True, sharey=True)
+ """
+ gridspec_kw = dict(gridspec_kw or {})
+ if height_ratios is not None:
+ if 'height_ratios' in gridspec_kw:
+ raise ValueError("'height_ratios' must not be defined both as "
+ "parameter and as key in 'gridspec_kw'")
+ gridspec_kw['height_ratios'] = height_ratios
+ if width_ratios is not None:
+ if 'width_ratios' in gridspec_kw:
+ raise ValueError("'width_ratios' must not be defined both as "
+ "parameter and as key in 'gridspec_kw'")
+ gridspec_kw['width_ratios'] = width_ratios
+
+ gs = self.add_gridspec(nrows, ncols, figure=self, **gridspec_kw)
+ axs = gs.subplots(sharex=sharex, sharey=sharey, squeeze=squeeze,
+ subplot_kw=subplot_kw)
+ return axs
+
+ def delaxes(self, ax):
+ """
+ Remove the `~.axes.Axes` *ax* from the figure; update the current Axes.
+ """
+
+ def _reset_locators_and_formatters(axis):
+ # Set the formatters and locators to be associated with axis
+ # (where previously they may have been associated with another
+ # Axis instance)
+ axis.get_major_formatter().set_axis(axis)
+ axis.get_major_locator().set_axis(axis)
+ axis.get_minor_formatter().set_axis(axis)
+ axis.get_minor_locator().set_axis(axis)
+
+ def _break_share_link(ax, grouper):
+ siblings = grouper.get_siblings(ax)
+ if len(siblings) > 1:
+ grouper.remove(ax)
+ for last_ax in siblings:
+ if ax is not last_ax:
+ return last_ax
+ return None
+
+ self._axstack.remove(ax)
+ self._axobservers.process("_axes_change_event", self)
+ self.stale = True
+ self._localaxes.remove(ax)
+ self.canvas.release_mouse(ax)
+
+ # Break link between any shared axes
+ for name in ax._axis_names:
+ last_ax = _break_share_link(ax, ax._shared_axes[name])
+ if last_ax is not None:
+ _reset_locators_and_formatters(getattr(last_ax, f"{name}axis"))
+
+ # Break link between any twinned axes
+ _break_share_link(ax, ax._twinned_axes)
+
+ def clear(self, keep_observers=False):
+ """
+ Clear the figure.
+
+ Parameters
+ ----------
+ keep_observers : bool, default: False
+ Set *keep_observers* to True if, for example,
+ a gui widget is tracking the Axes in the figure.
+ """
+ self.suppressComposite = None
+
+ # first clear the axes in any subfigures
+ for subfig in self.subfigs:
+ subfig.clear(keep_observers=keep_observers)
+ self.subfigs = []
+
+ for ax in tuple(self.axes): # Iterate over the copy.
+ ax.clear()
+ self.delaxes(ax) # Remove ax from self._axstack.
+
+ self.artists = []
+ self.lines = []
+ self.patches = []
+ self.texts = []
+ self.images = []
+ self.legends = []
+ if not keep_observers:
+ self._axobservers = cbook.CallbackRegistry()
+ self._suptitle = None
+ self._supxlabel = None
+ self._supylabel = None
+
+ self.stale = True
+
+ # synonym for `clear`.
+ def clf(self, keep_observers=False):
+ """
+ [*Discouraged*] Alias for the `clear()` method.
+
+ .. admonition:: Discouraged
+
+ The use of ``clf()`` is discouraged. Use ``clear()`` instead.
+
+ Parameters
+ ----------
+ keep_observers : bool, default: False
+ Set *keep_observers* to True if, for example,
+ a gui widget is tracking the Axes in the figure.
+ """
+ return self.clear(keep_observers=keep_observers)
+
+ # Note: the docstring below is modified with replace for the pyplot
+ # version of this function because the method name differs (plt.figlegend)
+ # the replacements are:
+ # " legend(" -> " figlegend(" for the signatures
+ # "fig.legend(" -> "plt.figlegend" for the code examples
+ # "ax.plot" -> "plt.plot" for consistency in using pyplot when able
+ @_docstring.dedent_interpd
+ def legend(self, *args, **kwargs):
+ """
+ Place a legend on the figure.
+
+ Call signatures::
+
+ legend()
+ legend(handles, labels)
+ legend(handles=handles)
+ legend(labels)
+
+ The call signatures correspond to the following different ways to use
+ this method:
+
+ **1. Automatic detection of elements to be shown in the legend**
+
+ The elements to be added to the legend are automatically determined,
+ when you do not pass in any extra arguments.
+
+ In this case, the labels are taken from the artist. You can specify
+ them either at artist creation or by calling the
+ :meth:`~.Artist.set_label` method on the artist::
+
+ ax.plot([1, 2, 3], label='Inline label')
+ fig.legend()
+
+ or::
+
+ line, = ax.plot([1, 2, 3])
+ line.set_label('Label via method')
+ fig.legend()
+
+ Specific lines can be excluded from the automatic legend element
+ selection by defining a label starting with an underscore.
+ This is default for all artists, so calling `.Figure.legend` without
+ any arguments and without setting the labels manually will result in
+ no legend being drawn.
+
+
+ **2. Explicitly listing the artists and labels in the legend**
+
+ For full control of which artists have a legend entry, it is possible
+ to pass an iterable of legend artists followed by an iterable of
+ legend labels respectively::
+
+ fig.legend([line1, line2, line3], ['label1', 'label2', 'label3'])
+
+
+ **3. Explicitly listing the artists in the legend**
+
+ This is similar to 2, but the labels are taken from the artists'
+ label properties. Example::
+
+ line1, = ax1.plot([1, 2, 3], label='label1')
+ line2, = ax2.plot([1, 2, 3], label='label2')
+ fig.legend(handles=[line1, line2])
+
+
+ **4. Labeling existing plot elements**
+
+ .. admonition:: Discouraged
+
+ This call signature is discouraged, because the relation between
+ plot elements and labels is only implicit by their order and can
+ easily be mixed up.
+
+ To make a legend for all artists on all Axes, call this function with
+ an iterable of strings, one for each legend item. For example::
+
+ fig, (ax1, ax2) = plt.subplots(1, 2)
+ ax1.plot([1, 3, 5], color='blue')
+ ax2.plot([2, 4, 6], color='red')
+ fig.legend(['the blues', 'the reds'])
+
+
+ Parameters
+ ----------
+ handles : list of `.Artist`, optional
+ A list of Artists (lines, patches) to be added to the legend.
+ Use this together with *labels*, if you need full control on what
+ is shown in the legend and the automatic mechanism described above
+ is not sufficient.
+
+ The length of handles and labels should be the same in this
+ case. If they are not, they are truncated to the smaller length.
+
+ labels : list of str, optional
+ A list of labels to show next to the artists.
+ Use this together with *handles*, if you need full control on what
+ is shown in the legend and the automatic mechanism described above
+ is not sufficient.
+
+ Returns
+ -------
+ `~matplotlib.legend.Legend`
+
+ Other Parameters
+ ----------------
+ %(_legend_kw_figure)s
+
+ See Also
+ --------
+ .Axes.legend
+
+ Notes
+ -----
+ Some artists are not supported by this function. See
+ :doc:`/tutorials/intermediate/legend_guide` for details.
+ """
+
+ handles, labels, extra_args, kwargs = mlegend._parse_legend_args(
+ self.axes,
+ *args,
+ **kwargs)
+ # check for third arg
+ if len(extra_args):
+ # _api.warn_deprecated(
+ # "2.1",
+ # message="Figure.legend will accept no more than two "
+ # "positional arguments in the future. Use "
+ # "'fig.legend(handles, labels, loc=location)' "
+ # "instead.")
+ # kwargs['loc'] = extra_args[0]
+ # extra_args = extra_args[1:]
+ pass
+ transform = kwargs.pop('bbox_transform', self.transSubfigure)
+ # explicitly set the bbox transform if the user hasn't.
+ l = mlegend.Legend(self, handles, labels, *extra_args,
+ bbox_transform=transform, **kwargs)
+ self.legends.append(l)
+ l._remove_method = self.legends.remove
+ self.stale = True
+ return l
+
+ @_docstring.dedent_interpd
+ def text(self, x, y, s, fontdict=None, **kwargs):
+ """
+ Add text to figure.
+
+ Parameters
+ ----------
+ x, y : float
+ The position to place the text. By default, this is in figure
+ coordinates, floats in [0, 1]. The coordinate system can be changed
+ using the *transform* keyword.
+
+ s : str
+ The text string.
+
+ fontdict : dict, optional
+ A dictionary to override the default text properties. If not given,
+ the defaults are determined by :rc:`font.*`. Properties passed as
+ *kwargs* override the corresponding ones given in *fontdict*.
+
+ Returns
+ -------
+ `~.text.Text`
+
+ Other Parameters
+ ----------------
+ **kwargs : `~matplotlib.text.Text` properties
+ Other miscellaneous text parameters.
+
+ %(Text:kwdoc)s
+
+ See Also
+ --------
+ .Axes.text
+ .pyplot.text
+ """
+ effective_kwargs = {
+ 'transform': self.transSubfigure,
+ **(fontdict if fontdict is not None else {}),
+ **kwargs,
+ }
+ text = Text(x=x, y=y, text=s, **effective_kwargs)
+ text.set_figure(self)
+ text.stale_callback = _stale_figure_callback
+
+ self.texts.append(text)
+ text._remove_method = self.texts.remove
+ self.stale = True
+ return text
+
+ @_docstring.dedent_interpd
+ def colorbar(
+ self, mappable, cax=None, ax=None, use_gridspec=True, **kwargs):
+ """
+ Add a colorbar to a plot.
+
+ Parameters
+ ----------
+ mappable
+ The `matplotlib.cm.ScalarMappable` (i.e., `.AxesImage`,
+ `.ContourSet`, etc.) described by this colorbar. This argument is
+ mandatory for the `.Figure.colorbar` method but optional for the
+ `.pyplot.colorbar` function, which sets the default to the current
+ image.
+
+ Note that one can create a `.ScalarMappable` "on-the-fly" to
+ generate colorbars not attached to a previously drawn artist, e.g.
+ ::
+
+ fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)
+
+ cax : `~matplotlib.axes.Axes`, optional
+ Axes into which the colorbar will be drawn. If `None`, then a new
+ Axes is created and the space for it will be stolen from the Axes(s)
+ specified in *ax*.
+
+ ax : `~matplotlib.axes.Axes` or iterable or `numpy.ndarray` of Axes, optional
+ The one or more parent Axes from which space for a new colorbar Axes
+ will be stolen. This parameter is only used if *cax* is not set.
+
+ Defaults to the Axes that contains the mappable used to create the
+ colorbar.
+
+ use_gridspec : bool, optional
+ If *cax* is ``None``, a new *cax* is created as an instance of
+ Axes. If *ax* is positioned with a subplotspec and *use_gridspec*
+ is ``True``, then *cax* is also positioned with a subplotspec.
+
+ Returns
+ -------
+ colorbar : `~matplotlib.colorbar.Colorbar`
+
+ Other Parameters
+ ----------------
+ %(_make_axes_kw_doc)s
+ %(_colormap_kw_doc)s
+
+ Notes
+ -----
+ If *mappable* is a `~.contour.ContourSet`, its *extend* kwarg is
+ included automatically.
+
+ The *shrink* kwarg provides a simple way to scale the colorbar with
+ respect to the axes. Note that if *cax* is specified, it determines the
+ size of the colorbar and *shrink* and *aspect* kwargs are ignored.
+
+ For more precise control, you can manually specify the positions of the
+ axes objects in which the mappable and the colorbar are drawn. In this
+ case, do not use any of the axes properties kwargs.
+
+ It is known that some vector graphics viewers (svg and pdf) renders
+ white gaps between segments of the colorbar. This is due to bugs in
+ the viewers, not Matplotlib. As a workaround, the colorbar can be
+ rendered with overlapping segments::
+
+ cbar = colorbar()
+ cbar.solids.set_edgecolor("face")
+ draw()
+
+ However, this has negative consequences in other circumstances, e.g.
+ with semi-transparent images (alpha < 1) and colorbar extensions;
+ therefore, this workaround is not used by default (see issue #1188).
+
+ """
+
+ if ax is None:
+ ax = getattr(mappable, "axes", None)
+
+ if (self.get_layout_engine() is not None and
+ not self.get_layout_engine().colorbar_gridspec):
+ use_gridspec = False
+ # Store the value of gca so that we can set it back later on.
+ if cax is None:
+ if ax is None:
+ _api.warn_deprecated("3.6", message=(
+ 'Unable to determine Axes to steal space for Colorbar. '
+ 'Using gca(), but will raise in the future. '
+ 'Either provide the *cax* argument to use as the Axes for '
+ 'the Colorbar, provide the *ax* argument to steal space '
+ 'from it, or add *mappable* to an Axes.'))
+ ax = self.gca()
+ current_ax = self.gca()
+ userax = False
+ if (use_gridspec
+ and isinstance(ax, mpl.axes._base._AxesBase)
+ and ax.get_subplotspec()):
+ cax, kwargs = cbar.make_axes_gridspec(ax, **kwargs)
+ else:
+ cax, kwargs = cbar.make_axes(ax, **kwargs)
+ cax.grid(visible=False, which='both', axis='both')
+ else:
+ userax = True
+
+ # need to remove kws that cannot be passed to Colorbar
+ NON_COLORBAR_KEYS = ['fraction', 'pad', 'shrink', 'aspect', 'anchor',
+ 'panchor']
+ cb_kw = {k: v for k, v in kwargs.items() if k not in NON_COLORBAR_KEYS}
+
+ cb = cbar.Colorbar(cax, mappable, **cb_kw)
+
+ if not userax:
+ self.sca(current_ax)
+ self.stale = True
+ return cb
+
+ def subplots_adjust(self, left=None, bottom=None, right=None, top=None,
+ wspace=None, hspace=None):
+ """
+ Adjust the subplot layout parameters.
+
+ Unset parameters are left unmodified; initial values are given by
+ :rc:`figure.subplot.[name]`.
+
+ Parameters
+ ----------
+ left : float, optional
+ The position of the left edge of the subplots,
+ as a fraction of the figure width.
+ right : float, optional
+ The position of the right edge of the subplots,
+ as a fraction of the figure width.
+ bottom : float, optional
+ The position of the bottom edge of the subplots,
+ as a fraction of the figure height.
+ top : float, optional
+ The position of the top edge of the subplots,
+ as a fraction of the figure height.
+ wspace : float, optional
+ The width of the padding between subplots,
+ as a fraction of the average Axes width.
+ hspace : float, optional
+ The height of the padding between subplots,
+ as a fraction of the average Axes height.
+ """
+ if (self.get_layout_engine() is not None and
+ not self.get_layout_engine().adjust_compatible):
+ _api.warn_external(
+ "This figure was using a layout engine that is "
+ "incompatible with subplots_adjust and/or tight_layout; "
+ "not calling subplots_adjust.")
+ return
+ self.subplotpars.update(left, bottom, right, top, wspace, hspace)
+ for ax in self.axes:
+ if ax.get_subplotspec() is not None:
+ ax._set_position(ax.get_subplotspec().get_position(self))
+ self.stale = True
+
+ def align_xlabels(self, axs=None):
+ """
+ Align the xlabels of subplots in the same subplot column if label
+ alignment is being done automatically (i.e. the label position is
+ not manually set).
+
+ Alignment persists for draw events after this is called.
+
+ If a label is on the bottom, it is aligned with labels on Axes that
+ also have their label on the bottom and that have the same
+ bottom-most subplot row. If the label is on the top,
+ it is aligned with labels on Axes with the same top-most row.
+
+ Parameters
+ ----------
+ axs : list of `~matplotlib.axes.Axes`
+ Optional list of (or `~numpy.ndarray`) `~matplotlib.axes.Axes`
+ to align the xlabels.
+ Default is to align all Axes on the figure.
+
+ See Also
+ --------
+ matplotlib.figure.Figure.align_ylabels
+ matplotlib.figure.Figure.align_labels
+
+ Notes
+ -----
+ This assumes that ``axs`` are from the same `.GridSpec`, so that
+ their `.SubplotSpec` positions correspond to figure positions.
+
+ Examples
+ --------
+ Example with rotated xtick labels::
+
+ fig, axs = plt.subplots(1, 2)
+ for tick in axs[0].get_xticklabels():
+ tick.set_rotation(55)
+ axs[0].set_xlabel('XLabel 0')
+ axs[1].set_xlabel('XLabel 1')
+ fig.align_xlabels()
+ """
+ if axs is None:
+ axs = self.axes
+ axs = [ax for ax in np.ravel(axs) if ax.get_subplotspec() is not None]
+ for ax in axs:
+ _log.debug(' Working on: %s', ax.get_xlabel())
+ rowspan = ax.get_subplotspec().rowspan
+ pos = ax.xaxis.get_label_position() # top or bottom
+ # Search through other axes for label positions that are same as
+ # this one and that share the appropriate row number.
+ # Add to a grouper associated with each axes of siblings.
+ # This list is inspected in `axis.draw` by
+ # `axis._update_label_position`.
+ for axc in axs:
+ if axc.xaxis.get_label_position() == pos:
+ rowspanc = axc.get_subplotspec().rowspan
+ if (pos == 'top' and rowspan.start == rowspanc.start or
+ pos == 'bottom' and rowspan.stop == rowspanc.stop):
+ # grouper for groups of xlabels to align
+ self._align_label_groups['x'].join(ax, axc)
+
+ def align_ylabels(self, axs=None):
+ """
+ Align the ylabels of subplots in the same subplot column if label
+ alignment is being done automatically (i.e. the label position is
+ not manually set).
+
+ Alignment persists for draw events after this is called.
+
+ If a label is on the left, it is aligned with labels on Axes that
+ also have their label on the left and that have the same
+ left-most subplot column. If the label is on the right,
+ it is aligned with labels on Axes with the same right-most column.
+
+ Parameters
+ ----------
+ axs : list of `~matplotlib.axes.Axes`
+ Optional list (or `~numpy.ndarray`) of `~matplotlib.axes.Axes`
+ to align the ylabels.
+ Default is to align all Axes on the figure.
+
+ See Also
+ --------
+ matplotlib.figure.Figure.align_xlabels
+ matplotlib.figure.Figure.align_labels
+
+ Notes
+ -----
+ This assumes that ``axs`` are from the same `.GridSpec`, so that
+ their `.SubplotSpec` positions correspond to figure positions.
+
+ Examples
+ --------
+ Example with large yticks labels::
+
+ fig, axs = plt.subplots(2, 1)
+ axs[0].plot(np.arange(0, 1000, 50))
+ axs[0].set_ylabel('YLabel 0')
+ axs[1].set_ylabel('YLabel 1')
+ fig.align_ylabels()
+ """
+ if axs is None:
+ axs = self.axes
+ axs = [ax for ax in np.ravel(axs) if ax.get_subplotspec() is not None]
+ for ax in axs:
+ _log.debug(' Working on: %s', ax.get_ylabel())
+ colspan = ax.get_subplotspec().colspan
+ pos = ax.yaxis.get_label_position() # left or right
+ # Search through other axes for label positions that are same as
+ # this one and that share the appropriate column number.
+ # Add to a list associated with each axes of siblings.
+ # This list is inspected in `axis.draw` by
+ # `axis._update_label_position`.
+ for axc in axs:
+ if axc.yaxis.get_label_position() == pos:
+ colspanc = axc.get_subplotspec().colspan
+ if (pos == 'left' and colspan.start == colspanc.start or
+ pos == 'right' and colspan.stop == colspanc.stop):
+ # grouper for groups of ylabels to align
+ self._align_label_groups['y'].join(ax, axc)
+
+ def align_labels(self, axs=None):
+ """
+ Align the xlabels and ylabels of subplots with the same subplots
+ row or column (respectively) if label alignment is being
+ done automatically (i.e. the label position is not manually set).
+
+ Alignment persists for draw events after this is called.
+
+ Parameters
+ ----------
+ axs : list of `~matplotlib.axes.Axes`
+ Optional list (or `~numpy.ndarray`) of `~matplotlib.axes.Axes`
+ to align the labels.
+ Default is to align all Axes on the figure.
+
+ See Also
+ --------
+ matplotlib.figure.Figure.align_xlabels
+
+ matplotlib.figure.Figure.align_ylabels
+ """
+ self.align_xlabels(axs=axs)
+ self.align_ylabels(axs=axs)
+
+ def add_gridspec(self, nrows=1, ncols=1, **kwargs):
+ """
+ Return a `.GridSpec` that has this figure as a parent. This allows
+ complex layout of Axes in the figure.
+
+ Parameters
+ ----------
+ nrows : int, default: 1
+ Number of rows in grid.
+
+ ncols : int, default: 1
+ Number of columns in grid.
+
+ Returns
+ -------
+ `.GridSpec`
+
+ Other Parameters
+ ----------------
+ **kwargs
+ Keyword arguments are passed to `.GridSpec`.
+
+ See Also
+ --------
+ matplotlib.pyplot.subplots
+
+ Examples
+ --------
+ Adding a subplot that spans two rows::
+
+ fig = plt.figure()
+ gs = fig.add_gridspec(2, 2)
+ ax1 = fig.add_subplot(gs[0, 0])
+ ax2 = fig.add_subplot(gs[1, 0])
+ # spans two rows:
+ ax3 = fig.add_subplot(gs[:, 1])
+
+ """
+
+ _ = kwargs.pop('figure', None) # pop in case user has added this...
+ gs = GridSpec(nrows=nrows, ncols=ncols, figure=self, **kwargs)
+ return gs
+
+ def subfigures(self, nrows=1, ncols=1, squeeze=True,
+ wspace=None, hspace=None,
+ width_ratios=None, height_ratios=None,
+ **kwargs):
+ """
+ Add a set of subfigures to this figure or subfigure.
+
+ A subfigure has the same artist methods as a figure, and is logically
+ the same as a figure, but cannot print itself.
+ See :doc:`/gallery/subplots_axes_and_figures/subfigures`.
+
+ .. note::
+ The *subfigure* concept is new in v3.4, and the API is still provisional.
+
+ Parameters
+ ----------
+ nrows, ncols : int, default: 1
+ Number of rows/columns of the subfigure grid.
+
+ squeeze : bool, default: True
+ If True, extra dimensions are squeezed out from the returned
+ array of subfigures.
+
+ wspace, hspace : float, default: None
+ The amount of width/height reserved for space between subfigures,
+ expressed as a fraction of the average subfigure width/height.
+ If not given, the values will be inferred from rcParams if using
+ constrained layout (see `~.ConstrainedLayoutEngine`), or zero if
+ not using a layout engine.
+
+ width_ratios : array-like of length *ncols*, optional
+ Defines the relative widths of the columns. Each column gets a
+ relative width of ``width_ratios[i] / sum(width_ratios)``.
+ If not given, all columns will have the same width.
+
+ height_ratios : array-like of length *nrows*, optional
+ Defines the relative heights of the rows. Each row gets a
+ relative height of ``height_ratios[i] / sum(height_ratios)``.
+ If not given, all rows will have the same height.
+ """
+ gs = GridSpec(nrows=nrows, ncols=ncols, figure=self,
+ wspace=wspace, hspace=hspace,
+ width_ratios=width_ratios,
+ height_ratios=height_ratios,
+ left=0, right=1, bottom=0, top=1)
+
+ sfarr = np.empty((nrows, ncols), dtype=object)
+ for i in range(ncols):
+ for j in range(nrows):
+ sfarr[j, i] = self.add_subfigure(gs[j, i], **kwargs)
+
+ if self.get_layout_engine() is None and (wspace is not None or
+ hspace is not None):
+ # Gridspec wspace and hspace is ignored on subfigure instantiation,
+ # and no space is left. So need to account for it here if required.
+ bottoms, tops, lefts, rights = gs.get_grid_positions(self)
+ for sfrow, bottom, top in zip(sfarr, bottoms, tops):
+ for sf, left, right in zip(sfrow, lefts, rights):
+ bbox = Bbox.from_extents(left, bottom, right, top)
+ sf._redo_transform_rel_fig(bbox=bbox)
+
+ if squeeze:
+ # Discarding unneeded dimensions that equal 1. If we only have one
+ # subfigure, just return it instead of a 1-element array.
+ return sfarr.item() if sfarr.size == 1 else sfarr.squeeze()
+ else:
+ # Returned axis array will be always 2-d, even if nrows=ncols=1.
+ return sfarr
+
+ def add_subfigure(self, subplotspec, **kwargs):
+ """
+ Add a `.SubFigure` to the figure as part of a subplot arrangement.
+
+ Parameters
+ ----------
+ subplotspec : `.gridspec.SubplotSpec`
+ Defines the region in a parent gridspec where the subfigure will
+ be placed.
+
+ Returns
+ -------
+ `.SubFigure`
+
+ Other Parameters
+ ----------------
+ **kwargs
+ Are passed to the `.SubFigure` object.
+
+ See Also
+ --------
+ .Figure.subfigures
+ """
+ sf = SubFigure(self, subplotspec, **kwargs)
+ self.subfigs += [sf]
+ return sf
+
+ def sca(self, a):
+ """Set the current Axes to be *a* and return *a*."""
+ self._axstack.bubble(a)
+ self._axobservers.process("_axes_change_event", self)
+ return a
+
+ def gca(self):
+ """
+ Get the current Axes.
+
+ If there is currently no Axes on this Figure, a new one is created
+ using `.Figure.add_subplot`. (To test whether there is currently an
+ Axes on a Figure, check whether ``figure.axes`` is empty. To test
+ whether there is currently a Figure on the pyplot figure stack, check
+ whether `.pyplot.get_fignums()` is empty.)
+ """
+ ax = self._axstack.current()
+ return ax if ax is not None else self.add_subplot()
+
+ def _gci(self):
+ # Helper for `~matplotlib.pyplot.gci`. Do not use elsewhere.
+ """
+ Get the current colorable artist.
+
+ Specifically, returns the current `.ScalarMappable` instance (`.Image`
+ created by `imshow` or `figimage`, `.Collection` created by `pcolor` or
+ `scatter`, etc.), or *None* if no such instance has been defined.
+
+ The current image is an attribute of the current Axes, or the nearest
+ earlier Axes in the current figure that contains an image.
+
+ Notes
+ -----
+ Historically, the only colorable artists were images; hence the name
+ ``gci`` (get current image).
+ """
+ # Look first for an image in the current Axes.
+ ax = self._axstack.current()
+ if ax is None:
+ return None
+ im = ax._gci()
+ if im is not None:
+ return im
+ # If there is no image in the current Axes, search for
+ # one in a previously created Axes. Whether this makes
+ # sense is debatable, but it is the documented behavior.
+ for ax in reversed(self.axes):
+ im = ax._gci()
+ if im is not None:
+ return im
+ return None
+
+ def _process_projection_requirements(
+ self, *args, axes_class=None, polar=False, projection=None,
+ **kwargs):
+ """
+ Handle the args/kwargs to add_axes/add_subplot/gca, returning::
+
+ (axes_proj_class, proj_class_kwargs)
+
+ which can be used for new Axes initialization/identification.
+ """
+ if axes_class is not None:
+ if polar or projection is not None:
+ raise ValueError(
+ "Cannot combine 'axes_class' and 'projection' or 'polar'")
+ projection_class = axes_class
+ else:
+
+ if polar:
+ if projection is not None and projection != 'polar':
+ raise ValueError(
+ f"polar={polar}, yet projection={projection!r}. "
+ "Only one of these arguments should be supplied."
+ )
+ projection = 'polar'
+
+ if isinstance(projection, str) or projection is None:
+ projection_class = projections.get_projection_class(projection)
+ elif hasattr(projection, '_as_mpl_axes'):
+ projection_class, extra_kwargs = projection._as_mpl_axes()
+ kwargs.update(**extra_kwargs)
+ else:
+ raise TypeError(
+ f"projection must be a string, None or implement a "
+ f"_as_mpl_axes method, not {projection!r}")
+ return projection_class, kwargs
+
+ def get_default_bbox_extra_artists(self):
+ bbox_artists = [artist for artist in self.get_children()
+ if (artist.get_visible() and artist.get_in_layout())]
+ for ax in self.axes:
+ if ax.get_visible():
+ bbox_artists.extend(ax.get_default_bbox_extra_artists())
+ return bbox_artists
+
+ def get_tightbbox(self, renderer=None, bbox_extra_artists=None):
+ """
+ Return a (tight) bounding box of the figure *in inches*.
+
+ Note that `.FigureBase` differs from all other artists, which return
+ their `.Bbox` in pixels.
+
+ Artists that have ``artist.set_in_layout(False)`` are not included
+ in the bbox.
+
+ Parameters
+ ----------
+ renderer : `.RendererBase` subclass
+ Renderer that will be used to draw the figures (i.e.
+ ``fig.canvas.get_renderer()``)
+
+ bbox_extra_artists : list of `.Artist` or ``None``
+ List of artists to include in the tight bounding box. If
+ ``None`` (default), then all artist children of each Axes are
+ included in the tight bounding box.
+
+ Returns
+ -------
+ `.BboxBase`
+ containing the bounding box (in figure inches).
+ """
+
+ if renderer is None:
+ renderer = self.figure._get_renderer()
+
+ bb = []
+ if bbox_extra_artists is None:
+ artists = self.get_default_bbox_extra_artists()
+ else:
+ artists = bbox_extra_artists
+
+ for a in artists:
+ bbox = a.get_tightbbox(renderer)
+ if bbox is not None:
+ bb.append(bbox)
+
+ for ax in self.axes:
+ if ax.get_visible():
+ # some axes don't take the bbox_extra_artists kwarg so we
+ # need this conditional....
+ try:
+ bbox = ax.get_tightbbox(
+ renderer, bbox_extra_artists=bbox_extra_artists)
+ except TypeError:
+ bbox = ax.get_tightbbox(renderer)
+ bb.append(bbox)
+ bb = [b for b in bb
+ if (np.isfinite(b.width) and np.isfinite(b.height)
+ and (b.width != 0 or b.height != 0))]
+
+ isfigure = hasattr(self, 'bbox_inches')
+ if len(bb) == 0:
+ if isfigure:
+ return self.bbox_inches
+ else:
+ # subfigures do not have bbox_inches, but do have a bbox
+ bb = [self.bbox]
+
+ _bbox = Bbox.union(bb)
+
+ if isfigure:
+ # transform from pixels to inches...
+ _bbox = TransformedBbox(_bbox, self.dpi_scale_trans.inverted())
+
+ return _bbox
+
+ @staticmethod
+ def _norm_per_subplot_kw(per_subplot_kw):
+ expanded = {}
+ for k, v in per_subplot_kw.items():
+ if isinstance(k, tuple):
+ for sub_key in k:
+ if sub_key in expanded:
+ raise ValueError(
+ f'The key {sub_key!r} appears multiple times.'
+ )
+ expanded[sub_key] = v
+ else:
+ if k in expanded:
+ raise ValueError(
+ f'The key {k!r} appears multiple times.'
+ )
+ expanded[k] = v
+ return expanded
+
+ @staticmethod
+ def _normalize_grid_string(layout):
+ if '\n' not in layout:
+ # single-line string
+ return [list(ln) for ln in layout.split(';')]
+ else:
+ # multi-line string
+ layout = inspect.cleandoc(layout)
+ return [list(ln) for ln in layout.strip('\n').split('\n')]
+
+ def subplot_mosaic(self, mosaic, *, sharex=False, sharey=False,
+ width_ratios=None, height_ratios=None,
+ empty_sentinel='.',
+ subplot_kw=None, per_subplot_kw=None, gridspec_kw=None):
+ """
+ Build a layout of Axes based on ASCII art or nested lists.
+
+ This is a helper function to build complex GridSpec layouts visually.
+
+ See :doc:`/gallery/subplots_axes_and_figures/mosaic`
+ for an example and full API documentation
+
+ Parameters
+ ----------
+ mosaic : list of list of {hashable or nested} or str
+
+ A visual layout of how you want your Axes to be arranged
+ labeled as strings. For example ::
+
+ x = [['A panel', 'A panel', 'edge'],
+ ['C panel', '.', 'edge']]
+
+ produces 4 Axes:
+
+ - 'A panel' which is 1 row high and spans the first two columns
+ - 'edge' which is 2 rows high and is on the right edge
+ - 'C panel' which in 1 row and 1 column wide in the bottom left
+ - a blank space 1 row and 1 column wide in the bottom center
+
+ Any of the entries in the layout can be a list of lists
+ of the same form to create nested layouts.
+
+ If input is a str, then it can either be a multi-line string of
+ the form ::
+
+ '''
+ AAE
+ C.E
+ '''
+
+ where each character is a column and each line is a row. Or it
+ can be a single-line string where rows are separated by ``;``::
+
+ 'AB;CC'
+
+ The string notation allows only single character Axes labels and
+ does not support nesting but is very terse.
+
+ The Axes identifiers may be `str` or a non-iterable hashable
+ object (e.g. `tuple` s may not be used).
+
+ sharex, sharey : bool, default: False
+ If True, the x-axis (*sharex*) or y-axis (*sharey*) will be shared
+ among all subplots. In that case, tick label visibility and axis
+ units behave as for `subplots`. If False, each subplot's x- or
+ y-axis will be independent.
+
+ width_ratios : array-like of length *ncols*, optional
+ Defines the relative widths of the columns. Each column gets a
+ relative width of ``width_ratios[i] / sum(width_ratios)``.
+ If not given, all columns will have the same width. Equivalent
+ to ``gridspec_kw={'width_ratios': [...]}``. In the case of nested
+ layouts, this argument applies only to the outer layout.
+
+ height_ratios : array-like of length *nrows*, optional
+ Defines the relative heights of the rows. Each row gets a
+ relative height of ``height_ratios[i] / sum(height_ratios)``.
+ If not given, all rows will have the same height. Equivalent
+ to ``gridspec_kw={'height_ratios': [...]}``. In the case of nested
+ layouts, this argument applies only to the outer layout.
+
+ subplot_kw : dict, optional
+ Dictionary with keywords passed to the `.Figure.add_subplot` call
+ used to create each subplot. These values may be overridden by
+ values in *per_subplot_kw*.
+
+ per_subplot_kw : dict, optional
+ A dictionary mapping the Axes identifiers or tuples of identifiers
+ to a dictionary of keyword arguments to be passed to the
+ `.Figure.add_subplot` call used to create each subplot. The values
+ in these dictionaries have precedence over the values in
+ *subplot_kw*.
+
+ If *mosaic* is a string, and thus all keys are single characters,
+ it is possible to use a single string instead of a tuple as keys;
+ i.e. ``"AB"`` is equivalent to ``("A", "B")``.
+
+ .. versionadded:: 3.7
+
+ gridspec_kw : dict, optional
+ Dictionary with keywords passed to the `.GridSpec` constructor used
+ to create the grid the subplots are placed on. In the case of
+ nested layouts, this argument applies only to the outer layout.
+ For more complex layouts, users should use `.Figure.subfigures`
+ to create the nesting.
+
+ empty_sentinel : object, optional
+ Entry in the layout to mean "leave this space empty". Defaults
+ to ``'.'``. Note, if *layout* is a string, it is processed via
+ `inspect.cleandoc` to remove leading white space, which may
+ interfere with using white-space as the empty sentinel.
+
+ Returns
+ -------
+ dict[label, Axes]
+ A dictionary mapping the labels to the Axes objects. The order of
+ the axes is left-to-right and top-to-bottom of their position in the
+ total layout.
+
+ """
+ subplot_kw = subplot_kw or {}
+ gridspec_kw = dict(gridspec_kw or {})
+ per_subplot_kw = per_subplot_kw or {}
+
+ if height_ratios is not None:
+ if 'height_ratios' in gridspec_kw:
+ raise ValueError("'height_ratios' must not be defined both as "
+ "parameter and as key in 'gridspec_kw'")
+ gridspec_kw['height_ratios'] = height_ratios
+ if width_ratios is not None:
+ if 'width_ratios' in gridspec_kw:
+ raise ValueError("'width_ratios' must not be defined both as "
+ "parameter and as key in 'gridspec_kw'")
+ gridspec_kw['width_ratios'] = width_ratios
+
+ # special-case string input
+ if isinstance(mosaic, str):
+ mosaic = self._normalize_grid_string(mosaic)
+ per_subplot_kw = {
+ tuple(k): v for k, v in per_subplot_kw.items()
+ }
+
+ per_subplot_kw = self._norm_per_subplot_kw(per_subplot_kw)
+
+ # Only accept strict bools to allow a possible future API expansion.
+ _api.check_isinstance(bool, sharex=sharex, sharey=sharey)
+
+ def _make_array(inp):
+ """
+ Convert input into 2D array
+
+ We need to have this internal function rather than
+ ``np.asarray(..., dtype=object)`` so that a list of lists
+ of lists does not get converted to an array of dimension >
+ 2
+
+ Returns
+ -------
+ 2D object array
+
+ """
+ r0, *rest = inp
+ if isinstance(r0, str):
+ raise ValueError('List mosaic specification must be 2D')
+ for j, r in enumerate(rest, start=1):
+ if isinstance(r, str):
+ raise ValueError('List mosaic specification must be 2D')
+ if len(r0) != len(r):
+ raise ValueError(
+ "All of the rows must be the same length, however "
+ f"the first row ({r0!r}) has length {len(r0)} "
+ f"and row {j} ({r!r}) has length {len(r)}."
+ )
+ out = np.zeros((len(inp), len(r0)), dtype=object)
+ for j, r in enumerate(inp):
+ for k, v in enumerate(r):
+ out[j, k] = v
+ return out
+
+ def _identify_keys_and_nested(mosaic):
+ """
+ Given a 2D object array, identify unique IDs and nested mosaics
+
+ Parameters
+ ----------
+ mosaic : 2D numpy object array
+
+ Returns
+ -------
+ unique_ids : tuple
+ The unique non-sub mosaic entries in this mosaic
+ nested : dict[tuple[int, int]], 2D object array
+ """
+ # make sure we preserve the user supplied order
+ unique_ids = cbook._OrderedSet()
+ nested = {}
+ for j, row in enumerate(mosaic):
+ for k, v in enumerate(row):
+ if v == empty_sentinel:
+ continue
+ elif not cbook.is_scalar_or_string(v):
+ nested[(j, k)] = _make_array(v)
+ else:
+ unique_ids.add(v)
+
+ return tuple(unique_ids), nested
+
+ def _do_layout(gs, mosaic, unique_ids, nested):
+ """
+ Recursively do the mosaic.
+
+ Parameters
+ ----------
+ gs : GridSpec
+ mosaic : 2D object array
+ The input converted to a 2D numpy array for this level.
+ unique_ids : tuple
+ The identified scalar labels at this level of nesting.
+ nested : dict[tuple[int, int]], 2D object array
+ The identified nested mosaics, if any.
+
+ Returns
+ -------
+ dict[label, Axes]
+ A flat dict of all of the Axes created.
+ """
+ output = dict()
+
+ # we need to merge together the Axes at this level and the axes
+ # in the (recursively) nested sub-mosaics so that we can add
+ # them to the figure in the "natural" order if you were to
+ # ravel in c-order all of the Axes that will be created
+ #
+ # This will stash the upper left index of each object (axes or
+ # nested mosaic) at this level
+ this_level = dict()
+
+ # go through the unique keys,
+ for name in unique_ids:
+ # sort out where each axes starts/ends
+ indx = np.argwhere(mosaic == name)
+ start_row, start_col = np.min(indx, axis=0)
+ end_row, end_col = np.max(indx, axis=0) + 1
+ # and construct the slice object
+ slc = (slice(start_row, end_row), slice(start_col, end_col))
+ # some light error checking
+ if (mosaic[slc] != name).any():
+ raise ValueError(
+ f"While trying to layout\n{mosaic!r}\n"
+ f"we found that the label {name!r} specifies a "
+ "non-rectangular or non-contiguous area.")
+ # and stash this slice for later
+ this_level[(start_row, start_col)] = (name, slc, 'axes')
+
+ # do the same thing for the nested mosaics (simpler because these
+ # can not be spans yet!)
+ for (j, k), nested_mosaic in nested.items():
+ this_level[(j, k)] = (None, nested_mosaic, 'nested')
+
+ # now go through the things in this level and add them
+ # in order left-to-right top-to-bottom
+ for key in sorted(this_level):
+ name, arg, method = this_level[key]
+ # we are doing some hokey function dispatch here based
+ # on the 'method' string stashed above to sort out if this
+ # element is an Axes or a nested mosaic.
+ if method == 'axes':
+ slc = arg
+ # add a single axes
+ if name in output:
+ raise ValueError(f"There are duplicate keys {name} "
+ f"in the layout\n{mosaic!r}")
+ ax = self.add_subplot(
+ gs[slc], **{
+ 'label': str(name),
+ **subplot_kw,
+ **per_subplot_kw.get(name, {})
+ }
+ )
+ output[name] = ax
+ elif method == 'nested':
+ nested_mosaic = arg
+ j, k = key
+ # recursively add the nested mosaic
+ rows, cols = nested_mosaic.shape
+ nested_output = _do_layout(
+ gs[j, k].subgridspec(rows, cols),
+ nested_mosaic,
+ *_identify_keys_and_nested(nested_mosaic)
+ )
+ overlap = set(output) & set(nested_output)
+ if overlap:
+ raise ValueError(
+ f"There are duplicate keys {overlap} "
+ f"between the outer layout\n{mosaic!r}\n"
+ f"and the nested layout\n{nested_mosaic}"
+ )
+ output.update(nested_output)
+ else:
+ raise RuntimeError("This should never happen")
+ return output
+
+ mosaic = _make_array(mosaic)
+ rows, cols = mosaic.shape
+ gs = self.add_gridspec(rows, cols, **gridspec_kw)
+ ret = _do_layout(gs, mosaic, *_identify_keys_and_nested(mosaic))
+ ax0 = next(iter(ret.values()))
+ for ax in ret.values():
+ if sharex:
+ ax.sharex(ax0)
+ ax._label_outer_xaxis(check_patch=True)
+ if sharey:
+ ax.sharey(ax0)
+ ax._label_outer_yaxis(check_patch=True)
+ if extra := set(per_subplot_kw) - set(ret):
+ raise ValueError(
+ f"The keys {extra} are in *per_subplot_kw* "
+ "but not in the mosaic."
+ )
+ return ret
+
+ def _set_artist_props(self, a):
+ if a != self:
+ a.set_figure(self)
+ a.stale_callback = _stale_figure_callback
+ a.set_transform(self.transSubfigure)
+
+
+@_docstring.interpd
+class SubFigure(FigureBase):
+ """
+ Logical figure that can be placed inside a figure.
+
+ Typically instantiated using `.Figure.add_subfigure` or
+ `.SubFigure.add_subfigure`, or `.SubFigure.subfigures`. A subfigure has
+ the same methods as a figure except for those particularly tied to the size
+ or dpi of the figure, and is confined to a prescribed region of the figure.
+ For example the following puts two subfigures side-by-side::
+
+ fig = plt.figure()
+ sfigs = fig.subfigures(1, 2)
+ axsL = sfigs[0].subplots(1, 2)
+ axsR = sfigs[1].subplots(2, 1)
+
+ See :doc:`/gallery/subplots_axes_and_figures/subfigures`
+
+ .. note::
+ The *subfigure* concept is new in v3.4, and the API is still provisional.
+ """
+ callbacks = _api.deprecated(
+ "3.6", alternative=("the 'resize_event' signal in "
+ "Figure.canvas.callbacks")
+ )(property(lambda self: self._fig_callbacks))
+
+ def __init__(self, parent, subplotspec, *,
+ facecolor=None,
+ edgecolor=None,
+ linewidth=0.0,
+ frameon=None,
+ **kwargs):
+ """
+ Parameters
+ ----------
+ parent : `.Figure` or `.SubFigure`
+ Figure or subfigure that contains the SubFigure. SubFigures
+ can be nested.
+
+ subplotspec : `.gridspec.SubplotSpec`
+ Defines the region in a parent gridspec where the subfigure will
+ be placed.
+
+ facecolor : default: :rc:`figure.facecolor`
+ The figure patch face color.
+
+ edgecolor : default: :rc:`figure.edgecolor`
+ The figure patch edge color.
+
+ linewidth : float
+ The linewidth of the frame (i.e. the edge linewidth of the figure
+ patch).
+
+ frameon : bool, default: :rc:`figure.frameon`
+ If ``False``, suppress drawing the figure background patch.
+
+ Other Parameters
+ ----------------
+ **kwargs : `.SubFigure` properties, optional
+
+ %(SubFigure:kwdoc)s
+ """
+ super().__init__(**kwargs)
+ 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']
+
+ self._subplotspec = subplotspec
+ self._parent = parent
+ self.figure = parent.figure
+ self._fig_callbacks = parent._fig_callbacks
+
+ # subfigures use the parent axstack
+ self._axstack = parent._axstack
+ self.subplotpars = parent.subplotpars
+ self.dpi_scale_trans = parent.dpi_scale_trans
+ self._axobservers = parent._axobservers
+ self.canvas = parent.canvas
+ self.transFigure = parent.transFigure
+ self.bbox_relative = None
+ self._redo_transform_rel_fig()
+ self.figbbox = self._parent.figbbox
+ self.bbox = TransformedBbox(self.bbox_relative,
+ self._parent.transSubfigure)
+ self.transSubfigure = BboxTransformTo(self.bbox)
+
+ self.patch = Rectangle(
+ xy=(0, 0), width=1, height=1, visible=frameon,
+ facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth,
+ # Don't let the figure patch influence bbox calculation.
+ in_layout=False, transform=self.transSubfigure)
+ self._set_artist_props(self.patch)
+ self.patch.set_antialiased(False)
+
+ @property
+ def dpi(self):
+ return self._parent.dpi
+
+ @dpi.setter
+ def dpi(self, value):
+ self._parent.dpi = value
+
+ def get_dpi(self):
+ """
+ Return the resolution of the parent figure in dots-per-inch as a float.
+ """
+ return self._parent.dpi
+
+ def set_dpi(self, val):
+ """
+ Set the resolution of parent figure in dots-per-inch.
+
+ Parameters
+ ----------
+ val : float
+ """
+ self._parent.dpi = val
+ self.stale = True
+
+ def _get_renderer(self):
+ return self._parent._get_renderer()
+
+ def _redo_transform_rel_fig(self, bbox=None):
+ """
+ Make the transSubfigure bbox relative to Figure transform.
+
+ Parameters
+ ----------
+ bbox : bbox or None
+ If not None, then the bbox is used for relative bounding box.
+ Otherwise, it is calculated from the subplotspec.
+ """
+ if bbox is not None:
+ self.bbox_relative.p0 = bbox.p0
+ self.bbox_relative.p1 = bbox.p1
+ return
+ # need to figure out *where* this subplotspec is.
+ gs = self._subplotspec.get_gridspec()
+ wr = np.asarray(gs.get_width_ratios())
+ hr = np.asarray(gs.get_height_ratios())
+ dx = wr[self._subplotspec.colspan].sum() / wr.sum()
+ dy = hr[self._subplotspec.rowspan].sum() / hr.sum()
+ x0 = wr[:self._subplotspec.colspan.start].sum() / wr.sum()
+ y0 = 1 - hr[:self._subplotspec.rowspan.stop].sum() / hr.sum()
+ if self.bbox_relative is None:
+ self.bbox_relative = Bbox.from_bounds(x0, y0, dx, dy)
+ else:
+ self.bbox_relative.p0 = (x0, y0)
+ self.bbox_relative.p1 = (x0 + dx, y0 + dy)
+
+ def get_constrained_layout(self):
+ """
+ Return whether constrained layout is being used.
+
+ See :doc:`/tutorials/intermediate/constrainedlayout_guide`.
+ """
+ return self._parent.get_constrained_layout()
+
+ def get_constrained_layout_pads(self, relative=False):
+ """
+ Get padding for ``constrained_layout``.
+
+ Returns a list of ``w_pad, h_pad`` in inches and
+ ``wspace`` and ``hspace`` as fractions of the subplot.
+
+ See :doc:`/tutorials/intermediate/constrainedlayout_guide`.
+
+ Parameters
+ ----------
+ relative : bool
+ If `True`, then convert from inches to figure relative.
+ """
+ return self._parent.get_constrained_layout_pads(relative=relative)
+
+ def get_layout_engine(self):
+ return self._parent.get_layout_engine()
+
+ @property
+ def axes(self):
+ """
+ List of Axes in the SubFigure. You can access and modify the Axes
+ in the SubFigure through this list.
+
+ Modifying this list has no effect. Instead, use `~.SubFigure.add_axes`,
+ `~.SubFigure.add_subplot` or `~.SubFigure.delaxes` to add or remove an
+ Axes.
+
+ Note: The `.SubFigure.axes` property and `~.SubFigure.get_axes` method
+ are equivalent.
+ """
+ return self._localaxes[:]
+
+ get_axes = axes.fget
+
+ def draw(self, renderer):
+ # docstring inherited
+
+ # draw the figure bounding box, perhaps none for white figure
+ if not self.get_visible():
+ return
+
+ artists = self._get_draw_artists(renderer)
+
+ try:
+ renderer.open_group('subfigure', gid=self.get_gid())
+ self.patch.draw(renderer)
+ mimage._draw_list_compositing_images(
+ renderer, self, artists, self.figure.suppressComposite)
+ for sfig in self.subfigs:
+ sfig.draw(renderer)
+ renderer.close_group('subfigure')
+
+ finally:
+ self.stale = False
+
+
+@_docstring.interpd
+class Figure(FigureBase):
+ """
+ The top level container for all the plot elements.
+
+ Attributes
+ ----------
+ patch
+ The `.Rectangle` instance representing the figure background patch.
+
+ suppressComposite
+ For multiple images, the figure will make composite images
+ depending on the renderer option_image_nocomposite function. If
+ *suppressComposite* is a boolean, this will override the renderer.
+ """
+ # Remove the self._fig_callbacks properties on figure and subfigure
+ # after the deprecation expires.
+ callbacks = _api.deprecated(
+ "3.6", alternative=("the 'resize_event' signal in "
+ "Figure.canvas.callbacks")
+ )(property(lambda self: self._fig_callbacks))
+
+ def __str__(self):
+ return "Figure(%gx%g)" % tuple(self.bbox.size)
+
+ def __repr__(self):
+ return "<{clsname} size {h:g}x{w:g} with {naxes} Axes>".format(
+ clsname=self.__class__.__name__,
+ h=self.bbox.size[0], w=self.bbox.size[1],
+ naxes=len(self.axes),
+ )
+
+ @_api.make_keyword_only("3.6", "facecolor")
+ def __init__(self,
+ figsize=None,
+ dpi=None,
+ facecolor=None,
+ edgecolor=None,
+ linewidth=0.0,
+ frameon=None,
+ subplotpars=None, # rc figure.subplot.*
+ tight_layout=None, # rc figure.autolayout
+ constrained_layout=None, # rc figure.constrained_layout.use
+ *,
+ layout=None,
+ **kwargs
+ ):
+ """
+ Parameters
+ ----------
+ figsize : 2-tuple of floats, default: :rc:`figure.figsize`
+ Figure dimension ``(width, height)`` in inches.
+
+ dpi : float, default: :rc:`figure.dpi`
+ Dots per inch.
+
+ facecolor : default: :rc:`figure.facecolor`
+ The figure patch facecolor.
+
+ edgecolor : default: :rc:`figure.edgecolor`
+ The figure patch edge color.
+
+ linewidth : float
+ The linewidth of the frame (i.e. the edge linewidth of the figure
+ patch).
+
+ frameon : bool, default: :rc:`figure.frameon`
+ If ``False``, suppress drawing the figure background patch.
+
+ subplotpars : `SubplotParams`
+ Subplot parameters. If not given, the default subplot
+ parameters :rc:`figure.subplot.*` are used.
+
+ tight_layout : bool or dict, default: :rc:`figure.autolayout`
+ Whether to use the tight layout mechanism. See `.set_tight_layout`.
+
+ .. admonition:: Discouraged
+
+ The use of this parameter is discouraged. Please use
+ ``layout='tight'`` instead for the common case of
+ ``tight_layout=True`` and use `.set_tight_layout` otherwise.
+
+ constrained_layout : bool, default: :rc:`figure.constrained_layout.use`
+ This is equal to ``layout='constrained'``.
+
+ .. admonition:: Discouraged
+
+ The use of this parameter is discouraged. Please use
+ ``layout='constrained'`` instead.
+
+ layout : {'constrained', 'compressed', 'tight', 'none', `.LayoutEngine`, \
+None}, default: None
+ The layout mechanism for positioning of plot elements to avoid
+ overlapping Axes decorations (labels, ticks, etc). Note that
+ layout managers can have significant performance penalties.
+
+ - 'constrained': The constrained layout solver adjusts axes sizes
+ to avoid overlapping axes decorations. Can handle complex plot
+ layouts and colorbars, and is thus recommended.
+
+ See :doc:`/tutorials/intermediate/constrainedlayout_guide`
+ for examples.
+
+ - 'compressed': uses the same algorithm as 'constrained', but
+ removes extra space between fixed-aspect-ratio Axes. Best for
+ simple grids of axes.
+
+ - 'tight': Use the tight layout mechanism. This is a relatively
+ simple algorithm that adjusts the subplot parameters so that
+ decorations do not overlap. See `.Figure.set_tight_layout` for
+ further details.
+
+ - 'none': Do not use a layout engine.
+
+ - A `.LayoutEngine` instance. Builtin layout classes are
+ `.ConstrainedLayoutEngine` and `.TightLayoutEngine`, more easily
+ accessible by 'constrained' and 'tight'. Passing an instance
+ allows third parties to provide their own layout engine.
+
+ If not given, fall back to using the parameters *tight_layout* and
+ *constrained_layout*, including their config defaults
+ :rc:`figure.autolayout` and :rc:`figure.constrained_layout.use`.
+
+ Other Parameters
+ ----------------
+ **kwargs : `.Figure` properties, optional
+
+ %(Figure:kwdoc)s
+ """
+ super().__init__(**kwargs)
+ self._layout_engine = None
+
+ if layout is not None:
+ if (tight_layout is not None):
+ _api.warn_external(
+ "The Figure parameters 'layout' and 'tight_layout' cannot "
+ "be used together. Please use 'layout' only.")
+ if (constrained_layout is not None):
+ _api.warn_external(
+ "The Figure parameters 'layout' and 'constrained_layout' "
+ "cannot be used together. Please use 'layout' only.")
+ self.set_layout_engine(layout=layout)
+ elif tight_layout is not None:
+ if constrained_layout is not None:
+ _api.warn_external(
+ "The Figure parameters 'tight_layout' and "
+ "'constrained_layout' cannot be used together. Please use "
+ "'layout' parameter")
+ self.set_layout_engine(layout='tight')
+ if isinstance(tight_layout, dict):
+ self.get_layout_engine().set(**tight_layout)
+ elif constrained_layout is not None:
+ if isinstance(constrained_layout, dict):
+ self.set_layout_engine(layout='constrained')
+ self.get_layout_engine().set(**constrained_layout)
+ elif constrained_layout:
+ self.set_layout_engine(layout='constrained')
+
+ else:
+ # everything is None, so use default:
+ self.set_layout_engine(layout=layout)
+
+ self._fig_callbacks = cbook.CallbackRegistry(signals=["dpi_changed"])
+ # Callbacks traditionally associated with the canvas (and exposed with
+ # a proxy property), but that actually need to be on the figure for
+ # pickling.
+ self._canvas_callbacks = cbook.CallbackRegistry(
+ signals=FigureCanvasBase.events)
+ connect = self._canvas_callbacks._connect_picklable
+ self._mouse_key_ids = [
+ connect('key_press_event', backend_bases._key_handler),
+ connect('key_release_event', backend_bases._key_handler),
+ connect('key_release_event', backend_bases._key_handler),
+ connect('button_press_event', backend_bases._mouse_handler),
+ connect('button_release_event', backend_bases._mouse_handler),
+ connect('scroll_event', backend_bases._mouse_handler),
+ connect('motion_notify_event', backend_bases._mouse_handler),
+ ]
+ 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']
+
+ if not np.isfinite(figsize).all() or (np.array(figsize) < 0).any():
+ raise ValueError('figure size must be positive finite not '
+ f'{figsize}')
+ self.bbox_inches = Bbox.from_bounds(0, 0, *figsize)
+
+ self.dpi_scale_trans = Affine2D().scale(dpi)
+ # do not use property as it will trigger
+ self._dpi = dpi
+ self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans)
+ self.figbbox = self.bbox
+ self.transFigure = BboxTransformTo(self.bbox)
+ self.transSubfigure = self.transFigure
+
+ self.patch = Rectangle(
+ xy=(0, 0), width=1, height=1, visible=frameon,
+ facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth,
+ # Don't let the figure patch influence bbox calculation.
+ in_layout=False)
+ self._set_artist_props(self.patch)
+ self.patch.set_antialiased(False)
+
+ FigureCanvasBase(self) # Set self.canvas.
+
+ if subplotpars is None:
+ subplotpars = SubplotParams()
+
+ self.subplotpars = subplotpars
+
+ self._axstack = _AxesStack() # track all figure axes and current axes
+ self.clear()
+
+ def pick(self, mouseevent):
+ if not self.canvas.widgetlock.locked():
+ super().pick(mouseevent)
+
+ def _check_layout_engines_compat(self, old, new):
+ """
+ Helper for set_layout engine
+
+ If the figure has used the old engine and added a colorbar then the
+ value of colorbar_gridspec must be the same on the new engine.
+ """
+ if old is None or new is None:
+ return True
+ if old.colorbar_gridspec == new.colorbar_gridspec:
+ return True
+ # colorbar layout different, so check if any colorbars are on the
+ # figure...
+ for ax in self.axes:
+ if hasattr(ax, '_colorbar'):
+ # colorbars list themselves as a colorbar.
+ return False
+ return True
+
+ def set_layout_engine(self, layout=None, **kwargs):
+ """
+ Set the layout engine for this figure.
+
+ Parameters
+ ----------
+ layout: {'constrained', 'compressed', 'tight', 'none'} or \
+`LayoutEngine` or None
+
+ - 'constrained' will use `~.ConstrainedLayoutEngine`
+ - 'compressed' will also use `~.ConstrainedLayoutEngine`, but with
+ a correction that attempts to make a good layout for fixed-aspect
+ ratio Axes.
+ - 'tight' uses `~.TightLayoutEngine`
+ - 'none' removes layout engine.
+
+ If `None`, the behavior is controlled by :rc:`figure.autolayout`
+ (which if `True` behaves as if 'tight' was passed) and
+ :rc:`figure.constrained_layout.use` (which if `True` behaves as if
+ 'constrained' was passed). If both are `True`,
+ :rc:`figure.autolayout` takes priority.
+
+ Users and libraries can define their own layout engines and pass
+ the instance directly as well.
+
+ kwargs: dict
+ The keyword arguments are passed to the layout engine to set things
+ like padding and margin sizes. Only used if *layout* is a string.
+
+ """
+ if layout is None:
+ if mpl.rcParams['figure.autolayout']:
+ layout = 'tight'
+ elif mpl.rcParams['figure.constrained_layout.use']:
+ layout = 'constrained'
+ else:
+ self._layout_engine = None
+ return
+ if layout == 'tight':
+ new_layout_engine = TightLayoutEngine(**kwargs)
+ elif layout == 'constrained':
+ new_layout_engine = ConstrainedLayoutEngine(**kwargs)
+ elif layout == 'compressed':
+ new_layout_engine = ConstrainedLayoutEngine(compress=True,
+ **kwargs)
+ elif layout == 'none':
+ if self._layout_engine is not None:
+ new_layout_engine = PlaceHolderLayoutEngine(
+ self._layout_engine.adjust_compatible,
+ self._layout_engine.colorbar_gridspec
+ )
+ else:
+ new_layout_engine = None
+ elif isinstance(layout, LayoutEngine):
+ new_layout_engine = layout
+ else:
+ raise ValueError(f"Invalid value for 'layout': {layout!r}")
+
+ if self._check_layout_engines_compat(self._layout_engine,
+ new_layout_engine):
+ self._layout_engine = new_layout_engine
+ else:
+ raise RuntimeError('Colorbar layout of new layout engine not '
+ 'compatible with old engine, and a colorbar '
+ 'has been created. Engine not changed.')
+
+ def get_layout_engine(self):
+ return self._layout_engine
+
+ # TODO: I'd like to dynamically add the _repr_html_ method
+ # to the figure in the right context, but then IPython doesn't
+ # use it, for some reason.
+
+ def _repr_html_(self):
+ # We can't use "isinstance" here, because then we'd end up importing
+ # webagg unconditionally.
+ if 'WebAgg' in type(self.canvas).__name__:
+ from matplotlib.backends import backend_webagg
+ return backend_webagg.ipython_inline_display(self)
+
+ def show(self, warn=True):
+ """
+ If using a GUI backend with pyplot, display the figure window.
+
+ If the figure was not created using `~.pyplot.figure`, it will lack
+ a `~.backend_bases.FigureManagerBase`, and this method will raise an
+ AttributeError.
+
+ .. warning::
+
+ This does not manage an GUI event loop. Consequently, the figure
+ may only be shown briefly or not shown at all if you or your
+ environment are not managing an event loop.
+
+ Use cases for `.Figure.show` include running this from a GUI
+ application (where there is persistently an event loop running) or
+ from a shell, like IPython, that install an input hook to allow the
+ interactive shell to accept input while the figure is also being
+ shown and interactive. Some, but not all, GUI toolkits will
+ register an input hook on import. See :ref:`cp_integration` for
+ more details.
+
+ If you're in a shell without input hook integration or executing a
+ python script, you should use `matplotlib.pyplot.show` with
+ ``block=True`` instead, which takes care of starting and running
+ the event loop for you.
+
+ Parameters
+ ----------
+ warn : bool, default: True
+ If ``True`` and we are not running headless (i.e. on Linux with an
+ unset DISPLAY), issue warning when called on a non-GUI backend.
+
+ """
+ if self.canvas.manager is None:
+ raise AttributeError(
+ "Figure.show works only for figures managed by pyplot, "
+ "normally created by pyplot.figure()")
+ try:
+ self.canvas.manager.show()
+ except NonGuiException as exc:
+ if warn:
+ _api.warn_external(str(exc))
+
+ @property
+ def axes(self):
+ """
+ List of Axes in the Figure. You can access and modify the Axes in the
+ Figure through this list.
+
+ Do not modify the list itself. Instead, use `~Figure.add_axes`,
+ `~.Figure.add_subplot` or `~.Figure.delaxes` to add or remove an Axes.
+
+ Note: The `.Figure.axes` property and `~.Figure.get_axes` method are
+ equivalent.
+ """
+ return self._axstack.as_list()
+
+ get_axes = axes.fget
+
+ def _get_renderer(self):
+ if hasattr(self.canvas, 'get_renderer'):
+ return self.canvas.get_renderer()
+ else:
+ return _get_renderer(self)
+
+ def _get_dpi(self):
+ return self._dpi
+
+ def _set_dpi(self, dpi, forward=True):
+ """
+ Parameters
+ ----------
+ dpi : float
+
+ forward : bool
+ Passed on to `~.Figure.set_size_inches`
+ """
+ if dpi == self._dpi:
+ # We don't want to cause undue events in backends.
+ return
+ self._dpi = dpi
+ self.dpi_scale_trans.clear().scale(dpi)
+ w, h = self.get_size_inches()
+ self.set_size_inches(w, h, forward=forward)
+ self._fig_callbacks.process('dpi_changed', self)
+
+ dpi = property(_get_dpi, _set_dpi, doc="The resolution in dots per inch.")
+
+ def get_tight_layout(self):
+ """Return whether `.tight_layout` is called when drawing."""
+ return isinstance(self.get_layout_engine(), TightLayoutEngine)
+
+ @_api.deprecated("3.6", alternative="set_layout_engine",
+ pending=True)
+ def set_tight_layout(self, tight):
+ """
+ [*Discouraged*] Set whether and how `.tight_layout` is called when
+ drawing.
+
+ .. admonition:: Discouraged
+
+ This method is discouraged in favor of `~.set_layout_engine`.
+
+ Parameters
+ ----------
+ tight : bool or dict with keys "pad", "w_pad", "h_pad", "rect" or None
+ If a bool, sets whether to call `.tight_layout` upon drawing.
+ If ``None``, use :rc:`figure.autolayout` instead.
+ If a dict, pass it as kwargs to `.tight_layout`, overriding the
+ default paddings.
+ """
+ if tight is None:
+ tight = mpl.rcParams['figure.autolayout']
+ _tight = 'tight' if bool(tight) else 'none'
+ _tight_parameters = tight if isinstance(tight, dict) else {}
+ self.set_layout_engine(_tight, **_tight_parameters)
+ self.stale = True
+
+ def get_constrained_layout(self):
+ """
+ Return whether constrained layout is being used.
+
+ See :doc:`/tutorials/intermediate/constrainedlayout_guide`.
+ """
+ return isinstance(self.get_layout_engine(), ConstrainedLayoutEngine)
+
+ @_api.deprecated("3.6", alternative="set_layout_engine('constrained')",
+ pending=True)
+ def set_constrained_layout(self, constrained):
+ """
+ [*Discouraged*] Set whether ``constrained_layout`` is used upon
+ drawing.
+
+ If None, :rc:`figure.constrained_layout.use` value will be used.
+
+ When providing a dict containing the keys ``w_pad``, ``h_pad``
+ the default ``constrained_layout`` paddings will be
+ overridden. These pads are in inches and default to 3.0/72.0.
+ ``w_pad`` is the width padding and ``h_pad`` is the height padding.
+
+ .. admonition:: Discouraged
+
+ This method is discouraged in favor of `~.set_layout_engine`.
+
+ Parameters
+ ----------
+ constrained : bool or dict or None
+ """
+ if constrained is None:
+ constrained = mpl.rcParams['figure.constrained_layout.use']
+ _constrained = 'constrained' if bool(constrained) else 'none'
+ _parameters = constrained if isinstance(constrained, dict) else {}
+ self.set_layout_engine(_constrained, **_parameters)
+ self.stale = True
+
+ @_api.deprecated(
+ "3.6", alternative="figure.get_layout_engine().set()",
+ pending=True)
+ def set_constrained_layout_pads(self, **kwargs):
+ """
+ Set padding for ``constrained_layout``.
+
+ Tip: The parameters can be passed from a dictionary by using
+ ``fig.set_constrained_layout(**pad_dict)``.
+
+ See :doc:`/tutorials/intermediate/constrainedlayout_guide`.
+
+ Parameters
+ ----------
+ w_pad : float, default: :rc:`figure.constrained_layout.w_pad`
+ Width padding in inches. This is the pad around Axes
+ and is meant to make sure there is enough room for fonts to
+ look good. Defaults to 3 pts = 0.04167 inches
+
+ h_pad : float, default: :rc:`figure.constrained_layout.h_pad`
+ Height padding in inches. Defaults to 3 pts.
+
+ wspace : float, default: :rc:`figure.constrained_layout.wspace`
+ Width padding between subplots, expressed as a fraction of the
+ subplot width. The total padding ends up being w_pad + wspace.
+
+ hspace : float, default: :rc:`figure.constrained_layout.hspace`
+ Height padding between subplots, expressed as a fraction of the
+ subplot width. The total padding ends up being h_pad + hspace.
+
+ """
+ if isinstance(self.get_layout_engine(), ConstrainedLayoutEngine):
+ self.get_layout_engine().set(**kwargs)
+
+ @_api.deprecated("3.6", alternative="fig.get_layout_engine().get()",
+ pending=True)
+ def get_constrained_layout_pads(self, relative=False):
+ """
+ Get padding for ``constrained_layout``.
+
+ Returns a list of ``w_pad, h_pad`` in inches and
+ ``wspace`` and ``hspace`` as fractions of the subplot.
+ All values are None if ``constrained_layout`` is not used.
+
+ See :doc:`/tutorials/intermediate/constrainedlayout_guide`.
+
+ Parameters
+ ----------
+ relative : bool
+ If `True`, then convert from inches to figure relative.
+ """
+ if not isinstance(self.get_layout_engine(), ConstrainedLayoutEngine):
+ return None, None, None, None
+ info = self.get_layout_engine().get()
+ w_pad = info['w_pad']
+ h_pad = info['h_pad']
+ wspace = info['wspace']
+ hspace = info['hspace']
+
+ if relative and (w_pad is not None or h_pad is not None):
+ renderer = self._get_renderer()
+ dpi = renderer.dpi
+ w_pad = w_pad * dpi / renderer.width
+ h_pad = h_pad * dpi / renderer.height
+
+ return w_pad, h_pad, wspace, hspace
+
+ def set_canvas(self, canvas):
+ """
+ Set the canvas that contains the figure
+
+ Parameters
+ ----------
+ canvas : FigureCanvas
+ """
+ self.canvas = canvas
+
+ @_docstring.interpd
+ def figimage(self, X, xo=0, yo=0, alpha=None, norm=None, cmap=None,
+ vmin=None, vmax=None, origin=None, resize=False, **kwargs):
+ """
+ Add a non-resampled image to the figure.
+
+ The image is attached to the lower or upper left corner depending on
+ *origin*.
+
+ Parameters
+ ----------
+ X
+ The image data. This is an array of one of the following shapes:
+
+ - (M, N): an image with scalar data. Color-mapping is controlled
+ by *cmap*, *norm*, *vmin*, and *vmax*.
+ - (M, N, 3): an image with RGB values (0-1 float or 0-255 int).
+ - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int),
+ i.e. including transparency.
+
+ xo, yo : int
+ The *x*/*y* image offset in pixels.
+
+ alpha : None or float
+ The alpha blending value.
+
+ %(cmap_doc)s
+
+ This parameter is ignored if *X* is RGB(A).
+
+ %(norm_doc)s
+
+ This parameter is ignored if *X* is RGB(A).
+
+ %(vmin_vmax_doc)s
+
+ This parameter is ignored if *X* is RGB(A).
+
+ origin : {'upper', 'lower'}, default: :rc:`image.origin`
+ Indicates where the [0, 0] index of the array is in the upper left
+ or lower left corner of the axes.
+
+ resize : bool
+ If *True*, resize the figure to match the given image size.
+
+ Returns
+ -------
+ `matplotlib.image.FigureImage`
+
+ Other Parameters
+ ----------------
+ **kwargs
+ Additional kwargs are `.Artist` kwargs passed on to `.FigureImage`.
+
+ Notes
+ -----
+ figimage complements the Axes image (`~matplotlib.axes.Axes.imshow`)
+ which will be resampled to fit the current Axes. If you want
+ a resampled image to fill the entire figure, you can define an
+ `~matplotlib.axes.Axes` with extent [0, 0, 1, 1].
+
+ Examples
+ --------
+ ::
+
+ f = plt.figure()
+ nx = int(f.get_figwidth() * f.dpi)
+ ny = int(f.get_figheight() * f.dpi)
+ data = np.random.random((ny, nx))
+ f.figimage(data)
+ plt.show()
+ """
+ if resize:
+ dpi = self.get_dpi()
+ figsize = [x / dpi for x in (X.shape[1], X.shape[0])]
+ self.set_size_inches(figsize, forward=True)
+
+ im = mimage.FigureImage(self, cmap=cmap, norm=norm,
+ offsetx=xo, offsety=yo,
+ origin=origin, **kwargs)
+ im.stale_callback = _stale_figure_callback
+
+ im.set_array(X)
+ im.set_alpha(alpha)
+ if norm is None:
+ im.set_clim(vmin, vmax)
+ self.images.append(im)
+ im._remove_method = self.images.remove
+ self.stale = True
+ return im
+
+ def set_size_inches(self, w, h=None, forward=True):
+ """
+ Set the figure size in inches.
+
+ Call signatures::
+
+ fig.set_size_inches(w, h) # OR
+ fig.set_size_inches((w, h))
+
+ Parameters
+ ----------
+ w : (float, float) or float
+ Width and height in inches (if height not specified as a separate
+ argument) or width.
+ h : float
+ Height in inches.
+ forward : bool, default: True
+ If ``True``, the canvas size is automatically updated, e.g.,
+ you can resize the figure window from the shell.
+
+ See Also
+ --------
+ matplotlib.figure.Figure.get_size_inches
+ matplotlib.figure.Figure.set_figwidth
+ matplotlib.figure.Figure.set_figheight
+
+ Notes
+ -----
+ To transform from pixels to inches divide by `Figure.dpi`.
+ """
+ if h is None: # Got called with a single pair as argument.
+ w, h = w
+ size = np.array([w, h])
+ if not np.isfinite(size).all() or (size < 0).any():
+ raise ValueError(f'figure size must be positive finite not {size}')
+ self.bbox_inches.p1 = size
+ if forward:
+ manager = self.canvas.manager
+ if manager is not None:
+ manager.resize(*(size * self.dpi).astype(int))
+ self.stale = True
+
+ def get_size_inches(self):
+ """
+ Return the current size of the figure in inches.
+
+ Returns
+ -------
+ ndarray
+ The size (width, height) of the figure in inches.
+
+ See Also
+ --------
+ matplotlib.figure.Figure.set_size_inches
+ matplotlib.figure.Figure.get_figwidth
+ matplotlib.figure.Figure.get_figheight
+
+ Notes
+ -----
+ The size in pixels can be obtained by multiplying with `Figure.dpi`.
+ """
+ return np.array(self.bbox_inches.p1)
+
+ def get_figwidth(self):
+ """Return the figure width in inches."""
+ return self.bbox_inches.width
+
+ def get_figheight(self):
+ """Return the figure height in inches."""
+ return self.bbox_inches.height
+
+ def get_dpi(self):
+ """Return the resolution in dots per inch as a float."""
+ return self.dpi
+
+ def set_dpi(self, val):
+ """
+ Set the resolution of the figure in dots-per-inch.
+
+ Parameters
+ ----------
+ val : float
+ """
+ self.dpi = val
+ self.stale = True
+
+ def set_figwidth(self, val, forward=True):
+ """
+ Set the width of the figure in inches.
+
+ Parameters
+ ----------
+ val : float
+ forward : bool
+ See `set_size_inches`.
+
+ See Also
+ --------
+ matplotlib.figure.Figure.set_figheight
+ matplotlib.figure.Figure.set_size_inches
+ """
+ self.set_size_inches(val, self.get_figheight(), forward=forward)
+
+ def set_figheight(self, val, forward=True):
+ """
+ Set the height of the figure in inches.
+
+ Parameters
+ ----------
+ val : float
+ forward : bool
+ See `set_size_inches`.
+
+ See Also
+ --------
+ matplotlib.figure.Figure.set_figwidth
+ matplotlib.figure.Figure.set_size_inches
+ """
+ self.set_size_inches(self.get_figwidth(), val, forward=forward)
+
+ def clear(self, keep_observers=False):
+ # docstring inherited
+ super().clear(keep_observers=keep_observers)
+ # FigureBase.clear does not clear toolbars, as
+ # only Figure can have toolbars
+ toolbar = self.canvas.toolbar
+ if toolbar is not None:
+ toolbar.update()
+
+ @_finalize_rasterization
+ @allow_rasterization
+ def draw(self, renderer):
+ # docstring inherited
+
+ # draw the figure bounding box, perhaps none for white figure
+ if not self.get_visible():
+ return
+
+ artists = self._get_draw_artists(renderer)
+ try:
+ renderer.open_group('figure', gid=self.get_gid())
+ if self.axes and self.get_layout_engine() is not None:
+ try:
+ self.get_layout_engine().execute(self)
+ except ValueError:
+ pass
+ # ValueError can occur when resizing a window.
+
+ self.patch.draw(renderer)
+ mimage._draw_list_compositing_images(
+ renderer, self, artists, self.suppressComposite)
+
+ for sfig in self.subfigs:
+ sfig.draw(renderer)
+
+ renderer.close_group('figure')
+ finally:
+ self.stale = False
+
+ DrawEvent("draw_event", self.canvas, renderer)._process()
+
+ def draw_without_rendering(self):
+ """
+ Draw the figure with no output. Useful to get the final size of
+ artists that require a draw before their size is known (e.g. text).
+ """
+ renderer = _get_renderer(self)
+ with renderer._draw_disabled():
+ self.draw(renderer)
+
+ def draw_artist(self, a):
+ """
+ Draw `.Artist` *a* only.
+ """
+ a.draw(self.canvas.get_renderer())
+
+ def __getstate__(self):
+ state = super().__getstate__()
+
+ # The canvas cannot currently be pickled, but this has the benefit
+ # of meaning that a figure can be detached from one canvas, and
+ # re-attached to another.
+ state.pop("canvas")
+
+ # discard any changes to the dpi due to pixel ratio changes
+ state["_dpi"] = state.get('_original_dpi', state['_dpi'])
+
+ # add version information to the state
+ state['__mpl_version__'] = mpl.__version__
+
+ # check whether the figure manager (if any) is registered with pyplot
+ from matplotlib import _pylab_helpers
+ if self.canvas.manager in _pylab_helpers.Gcf.figs.values():
+ state['_restore_to_pylab'] = True
+ return state
+
+ def __setstate__(self, state):
+ version = state.pop('__mpl_version__')
+ restore_to_pylab = state.pop('_restore_to_pylab', False)
+
+ if version != mpl.__version__:
+ _api.warn_external(
+ f"This figure was saved with matplotlib version {version} and "
+ f"is unlikely to function correctly.")
+
+ self.__dict__ = state
+
+ # re-initialise some of the unstored state information
+ FigureCanvasBase(self) # Set self.canvas.
+
+ if restore_to_pylab:
+ # lazy import to avoid circularity
+ import matplotlib.pyplot as plt
+ import matplotlib._pylab_helpers as pylab_helpers
+ allnums = plt.get_fignums()
+ num = max(allnums) + 1 if allnums else 1
+ backend = plt._get_backend_mod()
+ mgr = backend.new_figure_manager_given_figure(num, self)
+ pylab_helpers.Gcf._set_new_active_manager(mgr)
+ plt.draw_if_interactive()
+
+ self.stale = True
+
+ def add_axobserver(self, func):
+ """Whenever the Axes state change, ``func(self)`` will be called."""
+ # Connect a wrapper lambda and not func itself, to avoid it being
+ # weakref-collected.
+ self._axobservers.connect("_axes_change_event", lambda arg: func(arg))
+
+ def savefig(self, fname, *, transparent=None, **kwargs):
+ """
+ Save the current figure.
+
+ Call signature::
+
+ savefig(fname, *, dpi='figure', format=None, metadata=None,
+ bbox_inches=None, pad_inches=0.1,
+ facecolor='auto', edgecolor='auto',
+ backend=None, **kwargs
+ )
+
+ The available output formats depend on the backend being used.
+
+ Parameters
+ ----------
+ fname : str or path-like or binary file-like
+ A path, or a Python file-like object, or
+ possibly some backend-dependent object such as
+ `matplotlib.backends.backend_pdf.PdfPages`.
+
+ If *format* is set, it determines the output format, and the file
+ is saved as *fname*. Note that *fname* is used verbatim, and there
+ is no attempt to make the extension, if any, of *fname* match
+ *format*, and no extension is appended.
+
+ If *format* is not set, then the format is inferred from the
+ extension of *fname*, if there is one. If *format* is not
+ set and *fname* has no extension, then the file is saved with
+ :rc:`savefig.format` and the appropriate extension is appended to
+ *fname*.
+
+ Other Parameters
+ ----------------
+ dpi : float or 'figure', default: :rc:`savefig.dpi`
+ The resolution in dots per inch. If 'figure', use the figure's
+ dpi value.
+
+ format : str
+ The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when
+ this is unset is documented under *fname*.
+
+ metadata : dict, optional
+ Key/value pairs to store in the image metadata. The supported keys
+ and defaults depend on the image format and backend:
+
+ - 'png' with Agg backend: See the parameter ``metadata`` of
+ `~.FigureCanvasAgg.print_png`.
+ - 'pdf' with pdf backend: See the parameter ``metadata`` of
+ `~.backend_pdf.PdfPages`.
+ - 'svg' with svg backend: See the parameter ``metadata`` of
+ `~.FigureCanvasSVG.print_svg`.
+ - 'eps' and 'ps' with PS backend: Only 'Creator' is supported.
+
+ bbox_inches : str or `.Bbox`, default: :rc:`savefig.bbox`
+ Bounding box in inches: only the given portion of the figure is
+ saved. If 'tight', try to figure out the tight bbox of the figure.
+
+ pad_inches : float, default: :rc:`savefig.pad_inches`
+ Amount of padding around the figure when bbox_inches is 'tight'.
+
+ facecolor : color or 'auto', default: :rc:`savefig.facecolor`
+ The facecolor of the figure. If 'auto', use the current figure
+ facecolor.
+
+ edgecolor : color or 'auto', default: :rc:`savefig.edgecolor`
+ The edgecolor of the figure. If 'auto', use the current figure
+ edgecolor.
+
+ backend : str, optional
+ Use a non-default backend to render the file, e.g. to render a
+ png file with the "cairo" backend rather than the default "agg",
+ or a pdf file with the "pgf" backend rather than the default
+ "pdf". Note that the default backend is normally sufficient. See
+ :ref:`the-builtin-backends` for a list of valid backends for each
+ file format. Custom backends can be referenced as "module://...".
+
+ orientation : {'landscape', 'portrait'}
+ Currently only supported by the postscript backend.
+
+ papertype : str
+ One of 'letter', 'legal', 'executive', 'ledger', 'a0' through
+ 'a10', 'b0' through 'b10'. Only supported for postscript
+ output.
+
+ transparent : bool
+ If *True*, the Axes patches will all be transparent; the
+ Figure patch will also be transparent unless *facecolor*
+ and/or *edgecolor* are specified via kwargs.
+
+ If *False* has no effect and the color of the Axes and
+ Figure patches are unchanged (unless the Figure patch
+ is specified via the *facecolor* and/or *edgecolor* keyword
+ arguments in which case those colors are used).
+
+ The transparency of these patches will be restored to their
+ original values upon exit of this function.
+
+ This is useful, for example, for displaying
+ a plot on top of a colored background on a web page.
+
+ bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional
+ A list of extra artists that will be considered when the
+ tight bbox is calculated.
+
+ pil_kwargs : dict, optional
+ Additional keyword arguments that are passed to
+ `PIL.Image.Image.save` when saving the figure.
+
+ """
+
+ kwargs.setdefault('dpi', mpl.rcParams['savefig.dpi'])
+ if transparent is None:
+ transparent = mpl.rcParams['savefig.transparent']
+
+ with ExitStack() as stack:
+ if transparent:
+ kwargs.setdefault('facecolor', 'none')
+ kwargs.setdefault('edgecolor', 'none')
+ for ax in self.axes:
+ stack.enter_context(
+ ax.patch._cm_set(facecolor='none', edgecolor='none'))
+
+ self.canvas.print_figure(fname, **kwargs)
+
+ def ginput(self, n=1, timeout=30, show_clicks=True,
+ mouse_add=MouseButton.LEFT,
+ mouse_pop=MouseButton.RIGHT,
+ mouse_stop=MouseButton.MIDDLE):
+ """
+ Blocking call to interact with a figure.
+
+ Wait until the user clicks *n* times on the figure, and return the
+ coordinates of each click in a list.
+
+ There are three possible interactions:
+
+ - Add a point.
+ - Remove the most recently added point.
+ - Stop the interaction and return the points added so far.
+
+ The actions are assigned to mouse buttons via the arguments
+ *mouse_add*, *mouse_pop* and *mouse_stop*.
+
+ Parameters
+ ----------
+ n : int, default: 1
+ Number of mouse clicks to accumulate. If negative, accumulate
+ clicks until the input is terminated manually.
+ timeout : float, default: 30 seconds
+ Number of seconds to wait before timing out. If zero or negative
+ will never time out.
+ show_clicks : bool, default: True
+ If True, show a red cross at the location of each click.
+ mouse_add : `.MouseButton` or None, default: `.MouseButton.LEFT`
+ Mouse button used to add points.
+ mouse_pop : `.MouseButton` or None, default: `.MouseButton.RIGHT`
+ Mouse button used to remove the most recently added point.
+ mouse_stop : `.MouseButton` or None, default: `.MouseButton.MIDDLE`
+ Mouse button used to stop input.
+
+ Returns
+ -------
+ list of tuples
+ A list of the clicked (x, y) coordinates.
+
+ Notes
+ -----
+ The keyboard can also be used to select points in case your mouse
+ does not have one or more of the buttons. The delete and backspace
+ keys act like right-clicking (i.e., remove last point), the enter key
+ terminates input and any other key (not already used by the window
+ manager) selects a point.
+ """
+ clicks = []
+ marks = []
+
+ def handler(event):
+ is_button = event.name == "button_press_event"
+ is_key = event.name == "key_press_event"
+ # Quit (even if not in infinite mode; this is consistent with
+ # MATLAB and sometimes quite useful, but will require the user to
+ # test how many points were actually returned before using data).
+ if (is_button and event.button == mouse_stop
+ or is_key and event.key in ["escape", "enter"]):
+ self.canvas.stop_event_loop()
+ # Pop last click.
+ elif (is_button and event.button == mouse_pop
+ or is_key and event.key in ["backspace", "delete"]):
+ if clicks:
+ clicks.pop()
+ if show_clicks:
+ marks.pop().remove()
+ self.canvas.draw()
+ # Add new click.
+ elif (is_button and event.button == mouse_add
+ # On macOS/gtk, some keys return None.
+ or is_key and event.key is not None):
+ if event.inaxes:
+ clicks.append((event.xdata, event.ydata))
+ _log.info("input %i: %f, %f",
+ len(clicks), event.xdata, event.ydata)
+ if show_clicks:
+ line = mpl.lines.Line2D([event.xdata], [event.ydata],
+ marker="+", color="r")
+ event.inaxes.add_line(line)
+ marks.append(line)
+ self.canvas.draw()
+ if len(clicks) == n and n > 0:
+ self.canvas.stop_event_loop()
+
+ _blocking_input.blocking_input_loop(
+ self, ["button_press_event", "key_press_event"], timeout, handler)
+
+ # Cleanup.
+ for mark in marks:
+ mark.remove()
+ self.canvas.draw()
+
+ return clicks
+
+ def waitforbuttonpress(self, timeout=-1):
+ """
+ Blocking call to interact with the figure.
+
+ Wait for user input and return True if a key was pressed, False if a
+ mouse button was pressed and None if no input was given within
+ *timeout* seconds. Negative values deactivate *timeout*.
+ """
+ event = None
+
+ def handler(ev):
+ nonlocal event
+ event = ev
+ self.canvas.stop_event_loop()
+
+ _blocking_input.blocking_input_loop(
+ self, ["button_press_event", "key_press_event"], timeout, handler)
+
+ return None if event is None else event.name == "key_press_event"
+
+ @_api.deprecated("3.6", alternative="figure.get_layout_engine().execute()")
+ def execute_constrained_layout(self, renderer=None):
+ """
+ Use ``layoutgrid`` to determine pos positions within Axes.
+
+ See also `.set_constrained_layout_pads`.
+
+ Returns
+ -------
+ layoutgrid : private debugging object
+ """
+ if not isinstance(self.get_layout_engine(), ConstrainedLayoutEngine):
+ return None
+ return self.get_layout_engine().execute(self)
+
+ def tight_layout(self, *, pad=1.08, h_pad=None, w_pad=None, rect=None):
+ """
+ Adjust the padding between and around subplots.
+
+ To exclude an artist on the Axes from the bounding box calculation
+ that determines the subplot parameters (i.e. legend, or annotation),
+ set ``a.set_in_layout(False)`` for that artist.
+
+ Parameters
+ ----------
+ pad : float, default: 1.08
+ Padding between the figure edge and the edges of subplots,
+ as a fraction of the font size.
+ h_pad, w_pad : float, default: *pad*
+ Padding (height/width) between edges of adjacent subplots,
+ as a fraction of the font size.
+ rect : tuple (left, bottom, right, top), default: (0, 0, 1, 1)
+ A rectangle in normalized figure coordinates into which the whole
+ subplots area (including labels) will fit.
+
+ See Also
+ --------
+ .Figure.set_layout_engine
+ .pyplot.tight_layout
+ """
+ # note that here we do not permanently set the figures engine to
+ # tight_layout but rather just perform the layout in place and remove
+ # any previous engines.
+ engine = TightLayoutEngine(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
+ try:
+ previous_engine = self.get_layout_engine()
+ self.set_layout_engine(engine)
+ engine.execute(self)
+ if previous_engine is not None and not isinstance(
+ previous_engine, (TightLayoutEngine, PlaceHolderLayoutEngine)
+ ):
+ _api.warn_external('The figure layout has changed to tight')
+ finally:
+ self.set_layout_engine('none')
+
+
+def figaspect(arg):
+ """
+ Calculate the width and height for a figure with a specified aspect ratio.
+
+ While the height is taken from :rc:`figure.figsize`, the width is
+ adjusted to match the desired aspect ratio. Additionally, it is ensured
+ that the width is in the range [4., 16.] and the height is in the range
+ [2., 16.]. If necessary, the default height is adjusted to ensure this.
+
+ Parameters
+ ----------
+ arg : float or 2D array
+ If a float, this defines the aspect ratio (i.e. the ratio height /
+ width).
+ In case of an array the aspect ratio is number of rows / number of
+ columns, so that the array could be fitted in the figure undistorted.
+
+ Returns
+ -------
+ width, height : float
+ The figure size in inches.
+
+ Notes
+ -----
+ If you want to create an Axes within the figure, that still preserves the
+ aspect ratio, be sure to create it with equal width and height. See
+ examples below.
+
+ Thanks to Fernando Perez for this function.
+
+ Examples
+ --------
+ Make a figure twice as tall as it is wide::
+
+ w, h = figaspect(2.)
+ fig = Figure(figsize=(w, h))
+ ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
+ ax.imshow(A, **kwargs)
+
+ Make a figure with the proper aspect for an array::
+
+ A = rand(5, 3)
+ w, h = figaspect(A)
+ fig = Figure(figsize=(w, h))
+ ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
+ ax.imshow(A, **kwargs)
+ """
+
+ isarray = hasattr(arg, 'shape') and not np.isscalar(arg)
+
+ # min/max sizes to respect when autoscaling. If John likes the idea, they
+ # could become rc parameters, for now they're hardwired.
+ figsize_min = np.array((4.0, 2.0)) # min length for width/height
+ figsize_max = np.array((16.0, 16.0)) # max length for width/height
+
+ # Extract the aspect ratio of the array
+ if isarray:
+ nr, nc = arg.shape[:2]
+ arr_ratio = nr / nc
+ else:
+ arr_ratio = arg
+
+ # Height of user figure defaults
+ fig_height = mpl.rcParams['figure.figsize'][1]
+
+ # New size for the figure, keeping the aspect ratio of the caller
+ newsize = np.array((fig_height / arr_ratio, fig_height))
+
+ # Sanity checks, don't drop either dimension below figsize_min
+ newsize /= min(1.0, *(newsize / figsize_min))
+
+ # Avoid humongous windows as well
+ newsize /= max(1.0, *(newsize / figsize_max))
+
+ # Finally, if we have a really funky aspect ratio, break it but respect
+ # the min/max dimensions (we don't want figures 10 feet tall!)
+ newsize = np.clip(newsize, figsize_min, figsize_max)
+ return newsize
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/gridspec.py b/omnilmm/lib/python3.10/site-packages/matplotlib/gridspec.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee045ced315e772adfa384f833f74e8d32ce053a
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/gridspec.py
@@ -0,0 +1,739 @@
+r"""
+:mod:`~matplotlib.gridspec` contains classes that help to layout multiple
+`~.axes.Axes` in a grid-like pattern within a figure.
+
+The `GridSpec` specifies the overall grid structure. Individual cells within
+the grid are referenced by `SubplotSpec`\s.
+
+Often, users need not access this module directly, and can use higher-level
+methods like `~.pyplot.subplots`, `~.pyplot.subplot_mosaic` and
+`~.Figure.subfigures`. See the tutorial
+:doc:`/tutorials/intermediate/arranging_axes` for a guide.
+"""
+
+import copy
+import logging
+from numbers import Integral
+
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib import _api, _pylab_helpers, _tight_layout
+from matplotlib.transforms import Bbox
+
+_log = logging.getLogger(__name__)
+
+
+class GridSpecBase:
+ """
+ A base class of GridSpec that specifies the geometry of the grid
+ that a subplot will be placed.
+ """
+
+ def __init__(self, nrows, ncols, height_ratios=None, width_ratios=None):
+ """
+ Parameters
+ ----------
+ nrows, ncols : int
+ The number of rows and columns of the grid.
+ width_ratios : array-like of length *ncols*, optional
+ Defines the relative widths of the columns. Each column gets a
+ relative width of ``width_ratios[i] / sum(width_ratios)``.
+ If not given, all columns will have the same width.
+ height_ratios : array-like of length *nrows*, optional
+ Defines the relative heights of the rows. Each row gets a
+ relative height of ``height_ratios[i] / sum(height_ratios)``.
+ If not given, all rows will have the same height.
+ """
+ if not isinstance(nrows, Integral) or nrows <= 0:
+ raise ValueError(
+ f"Number of rows must be a positive integer, not {nrows!r}")
+ if not isinstance(ncols, Integral) or ncols <= 0:
+ raise ValueError(
+ f"Number of columns must be a positive integer, not {ncols!r}")
+ self._nrows, self._ncols = nrows, ncols
+ self.set_height_ratios(height_ratios)
+ self.set_width_ratios(width_ratios)
+
+ def __repr__(self):
+ height_arg = (', height_ratios=%r' % (self._row_height_ratios,)
+ if len(set(self._row_height_ratios)) != 1 else '')
+ width_arg = (', width_ratios=%r' % (self._col_width_ratios,)
+ if len(set(self._col_width_ratios)) != 1 else '')
+ return '{clsname}({nrows}, {ncols}{optionals})'.format(
+ clsname=self.__class__.__name__,
+ nrows=self._nrows,
+ ncols=self._ncols,
+ optionals=height_arg + width_arg,
+ )
+
+ nrows = property(lambda self: self._nrows,
+ doc="The number of rows in the grid.")
+ ncols = property(lambda self: self._ncols,
+ doc="The number of columns in the grid.")
+
+ def get_geometry(self):
+ """
+ Return a tuple containing the number of rows and columns in the grid.
+ """
+ return self._nrows, self._ncols
+
+ def get_subplot_params(self, figure=None):
+ # Must be implemented in subclasses
+ pass
+
+ def new_subplotspec(self, loc, rowspan=1, colspan=1):
+ """
+ Create and return a `.SubplotSpec` instance.
+
+ Parameters
+ ----------
+ loc : (int, int)
+ The position of the subplot in the grid as
+ ``(row_index, column_index)``.
+ rowspan, colspan : int, default: 1
+ The number of rows and columns the subplot should span in the grid.
+ """
+ loc1, loc2 = loc
+ subplotspec = self[loc1:loc1+rowspan, loc2:loc2+colspan]
+ return subplotspec
+
+ def set_width_ratios(self, width_ratios):
+ """
+ Set the relative widths of the columns.
+
+ *width_ratios* must be of length *ncols*. Each column gets a relative
+ width of ``width_ratios[i] / sum(width_ratios)``.
+ """
+ if width_ratios is None:
+ width_ratios = [1] * self._ncols
+ elif len(width_ratios) != self._ncols:
+ raise ValueError('Expected the given number of width ratios to '
+ 'match the number of columns of the grid')
+ self._col_width_ratios = width_ratios
+
+ def get_width_ratios(self):
+ """
+ Return the width ratios.
+
+ This is *None* if no width ratios have been set explicitly.
+ """
+ return self._col_width_ratios
+
+ def set_height_ratios(self, height_ratios):
+ """
+ Set the relative heights of the rows.
+
+ *height_ratios* must be of length *nrows*. Each row gets a relative
+ height of ``height_ratios[i] / sum(height_ratios)``.
+ """
+ if height_ratios is None:
+ height_ratios = [1] * self._nrows
+ elif len(height_ratios) != self._nrows:
+ raise ValueError('Expected the given number of height ratios to '
+ 'match the number of rows of the grid')
+ self._row_height_ratios = height_ratios
+
+ def get_height_ratios(self):
+ """
+ Return the height ratios.
+
+ This is *None* if no height ratios have been set explicitly.
+ """
+ return self._row_height_ratios
+
+ @_api.delete_parameter("3.7", "raw")
+ def get_grid_positions(self, fig, raw=False):
+ """
+ Return the positions of the grid cells in figure coordinates.
+
+ Parameters
+ ----------
+ fig : `~matplotlib.figure.Figure`
+ The figure the grid should be applied to. The subplot parameters
+ (margins and spacing between subplots) are taken from *fig*.
+ raw : bool, default: False
+ If *True*, the subplot parameters of the figure are not taken
+ into account. The grid spans the range [0, 1] in both directions
+ without margins and there is no space between grid cells. This is
+ used for constrained_layout.
+
+ Returns
+ -------
+ bottoms, tops, lefts, rights : array
+ The bottom, top, left, right positions of the grid cells in
+ figure coordinates.
+ """
+ nrows, ncols = self.get_geometry()
+
+ if raw:
+ left = 0.
+ right = 1.
+ bottom = 0.
+ top = 1.
+ wspace = 0.
+ hspace = 0.
+ else:
+ subplot_params = self.get_subplot_params(fig)
+ left = subplot_params.left
+ right = subplot_params.right
+ bottom = subplot_params.bottom
+ top = subplot_params.top
+ wspace = subplot_params.wspace
+ hspace = subplot_params.hspace
+ tot_width = right - left
+ tot_height = top - bottom
+
+ # calculate accumulated heights of columns
+ cell_h = tot_height / (nrows + hspace*(nrows-1))
+ sep_h = hspace * cell_h
+ norm = cell_h * nrows / sum(self._row_height_ratios)
+ cell_heights = [r * norm for r in self._row_height_ratios]
+ sep_heights = [0] + ([sep_h] * (nrows-1))
+ cell_hs = np.cumsum(np.column_stack([sep_heights, cell_heights]).flat)
+
+ # calculate accumulated widths of rows
+ cell_w = tot_width / (ncols + wspace*(ncols-1))
+ sep_w = wspace * cell_w
+ norm = cell_w * ncols / sum(self._col_width_ratios)
+ cell_widths = [r * norm for r in self._col_width_ratios]
+ sep_widths = [0] + ([sep_w] * (ncols-1))
+ cell_ws = np.cumsum(np.column_stack([sep_widths, cell_widths]).flat)
+
+ fig_tops, fig_bottoms = (top - cell_hs).reshape((-1, 2)).T
+ fig_lefts, fig_rights = (left + cell_ws).reshape((-1, 2)).T
+ return fig_bottoms, fig_tops, fig_lefts, fig_rights
+
+ @staticmethod
+ def _check_gridspec_exists(figure, nrows, ncols):
+ """
+ Check if the figure already has a gridspec with these dimensions,
+ or create a new one
+ """
+ for ax in figure.get_axes():
+ gs = ax.get_gridspec()
+ if gs is not None:
+ if hasattr(gs, 'get_topmost_subplotspec'):
+ # This is needed for colorbar gridspec layouts.
+ # This is probably OK because this whole logic tree
+ # is for when the user is doing simple things with the
+ # add_subplot command. For complicated layouts
+ # like subgridspecs the proper gridspec is passed in...
+ gs = gs.get_topmost_subplotspec().get_gridspec()
+ if gs.get_geometry() == (nrows, ncols):
+ return gs
+ # else gridspec not found:
+ return GridSpec(nrows, ncols, figure=figure)
+
+ def __getitem__(self, key):
+ """Create and return a `.SubplotSpec` instance."""
+ nrows, ncols = self.get_geometry()
+
+ def _normalize(key, size, axis): # Includes last index.
+ orig_key = key
+ if isinstance(key, slice):
+ start, stop, _ = key.indices(size)
+ if stop > start:
+ return start, stop - 1
+ raise IndexError("GridSpec slice would result in no space "
+ "allocated for subplot")
+ else:
+ if key < 0:
+ key = key + size
+ if 0 <= key < size:
+ return key, key
+ elif axis is not None:
+ raise IndexError(f"index {orig_key} is out of bounds for "
+ f"axis {axis} with size {size}")
+ else: # flat index
+ raise IndexError(f"index {orig_key} is out of bounds for "
+ f"GridSpec with size {size}")
+
+ if isinstance(key, tuple):
+ try:
+ k1, k2 = key
+ except ValueError as err:
+ raise ValueError("Unrecognized subplot spec") from err
+ num1, num2 = np.ravel_multi_index(
+ [_normalize(k1, nrows, 0), _normalize(k2, ncols, 1)],
+ (nrows, ncols))
+ else: # Single key
+ num1, num2 = _normalize(key, nrows * ncols, None)
+
+ return SubplotSpec(self, num1, num2)
+
+ def subplots(self, *, sharex=False, sharey=False, squeeze=True,
+ subplot_kw=None):
+ """
+ Add all subplots specified by this `GridSpec` to its parent figure.
+
+ See `.Figure.subplots` for detailed documentation.
+ """
+
+ figure = self.figure
+
+ if figure is None:
+ raise ValueError("GridSpec.subplots() only works for GridSpecs "
+ "created with a parent figure")
+
+ if not isinstance(sharex, str):
+ sharex = "all" if sharex else "none"
+ if not isinstance(sharey, str):
+ sharey = "all" if sharey else "none"
+
+ _api.check_in_list(["all", "row", "col", "none", False, True],
+ sharex=sharex, sharey=sharey)
+ if subplot_kw is None:
+ subplot_kw = {}
+ # don't mutate kwargs passed by user...
+ subplot_kw = subplot_kw.copy()
+
+ # Create array to hold all axes.
+ axarr = np.empty((self._nrows, self._ncols), dtype=object)
+ for row in range(self._nrows):
+ for col in range(self._ncols):
+ shared_with = {"none": None, "all": axarr[0, 0],
+ "row": axarr[row, 0], "col": axarr[0, col]}
+ subplot_kw["sharex"] = shared_with[sharex]
+ subplot_kw["sharey"] = shared_with[sharey]
+ axarr[row, col] = figure.add_subplot(
+ self[row, col], **subplot_kw)
+
+ # turn off redundant tick labeling
+ if sharex in ["col", "all"]:
+ for ax in axarr.flat:
+ ax._label_outer_xaxis(check_patch=True)
+ if sharey in ["row", "all"]:
+ for ax in axarr.flat:
+ ax._label_outer_yaxis(check_patch=True)
+
+ if squeeze:
+ # Discarding unneeded dimensions that equal 1. If we only have one
+ # subplot, just return it instead of a 1-element array.
+ return axarr.item() if axarr.size == 1 else axarr.squeeze()
+ else:
+ # Returned axis array will be always 2-d, even if nrows=ncols=1.
+ return axarr
+
+
+class GridSpec(GridSpecBase):
+ """
+ A grid layout to place subplots within a figure.
+
+ The location of the grid cells is determined in a similar way to
+ `~.figure.SubplotParams` using *left*, *right*, *top*, *bottom*, *wspace*
+ and *hspace*.
+
+ Indexing a GridSpec instance returns a `.SubplotSpec`.
+ """
+ def __init__(self, nrows, ncols, figure=None,
+ left=None, bottom=None, right=None, top=None,
+ wspace=None, hspace=None,
+ width_ratios=None, height_ratios=None):
+ """
+ Parameters
+ ----------
+ nrows, ncols : int
+ The number of rows and columns of the grid.
+
+ figure : `.Figure`, optional
+ Only used for constrained layout to create a proper layoutgrid.
+
+ left, right, top, bottom : float, optional
+ Extent of the subplots as a fraction of figure width or height.
+ Left cannot be larger than right, and bottom cannot be larger than
+ top. If not given, the values will be inferred from a figure or
+ rcParams at draw time. See also `GridSpec.get_subplot_params`.
+
+ wspace : float, optional
+ The amount of width reserved for space between subplots,
+ expressed as a fraction of the average axis width.
+ If not given, the values will be inferred from a figure or
+ rcParams when necessary. See also `GridSpec.get_subplot_params`.
+
+ hspace : float, optional
+ The amount of height reserved for space between subplots,
+ expressed as a fraction of the average axis height.
+ If not given, the values will be inferred from a figure or
+ rcParams when necessary. See also `GridSpec.get_subplot_params`.
+
+ width_ratios : array-like of length *ncols*, optional
+ Defines the relative widths of the columns. Each column gets a
+ relative width of ``width_ratios[i] / sum(width_ratios)``.
+ If not given, all columns will have the same width.
+
+ height_ratios : array-like of length *nrows*, optional
+ Defines the relative heights of the rows. Each row gets a
+ relative height of ``height_ratios[i] / sum(height_ratios)``.
+ If not given, all rows will have the same height.
+
+ """
+ self.left = left
+ self.bottom = bottom
+ self.right = right
+ self.top = top
+ self.wspace = wspace
+ self.hspace = hspace
+ self.figure = figure
+
+ super().__init__(nrows, ncols,
+ width_ratios=width_ratios,
+ height_ratios=height_ratios)
+
+ _AllowedKeys = ["left", "bottom", "right", "top", "wspace", "hspace"]
+
+ def update(self, **kwargs):
+ """
+ Update the subplot parameters of the grid.
+
+ Parameters that are not explicitly given are not changed. Setting a
+ parameter to *None* resets it to :rc:`figure.subplot.*`.
+
+ Parameters
+ ----------
+ left, right, top, bottom : float or None, optional
+ Extent of the subplots as a fraction of figure width or height.
+ wspace, hspace : float, optional
+ Spacing between the subplots as a fraction of the average subplot
+ width / height.
+ """
+ for k, v in kwargs.items():
+ if k in self._AllowedKeys:
+ setattr(self, k, v)
+ else:
+ raise AttributeError(f"{k} is an unknown keyword")
+ for figmanager in _pylab_helpers.Gcf.figs.values():
+ for ax in figmanager.canvas.figure.axes:
+ if ax.get_subplotspec() is not None:
+ ss = ax.get_subplotspec().get_topmost_subplotspec()
+ if ss.get_gridspec() == self:
+ ax._set_position(
+ ax.get_subplotspec().get_position(ax.figure))
+
+ def get_subplot_params(self, figure=None):
+ """
+ Return the `.SubplotParams` for the GridSpec.
+
+ In order of precedence the values are taken from
+
+ - non-*None* attributes of the GridSpec
+ - the provided *figure*
+ - :rc:`figure.subplot.*`
+
+ Note that the ``figure`` attribute of the GridSpec is always ignored.
+ """
+ if figure is None:
+ kw = {k: mpl.rcParams["figure.subplot."+k]
+ for k in self._AllowedKeys}
+ subplotpars = mpl.figure.SubplotParams(**kw)
+ else:
+ subplotpars = copy.copy(figure.subplotpars)
+
+ subplotpars.update(**{k: getattr(self, k) for k in self._AllowedKeys})
+
+ return subplotpars
+
+ def locally_modified_subplot_params(self):
+ """
+ Return a list of the names of the subplot parameters explicitly set
+ in the GridSpec.
+
+ This is a subset of the attributes of `.SubplotParams`.
+ """
+ return [k for k in self._AllowedKeys if getattr(self, k)]
+
+ def tight_layout(self, figure, renderer=None,
+ pad=1.08, h_pad=None, w_pad=None, rect=None):
+ """
+ Adjust subplot parameters to give specified padding.
+
+ Parameters
+ ----------
+ figure : `.Figure`
+ The figure.
+ renderer : `.RendererBase` subclass, optional
+ The renderer to be used.
+ pad : float
+ Padding between the figure edge and the edges of subplots, as a
+ fraction of the font-size.
+ h_pad, w_pad : float, optional
+ Padding (height/width) between edges of adjacent subplots.
+ Defaults to *pad*.
+ rect : tuple (left, bottom, right, top), default: None
+ (left, bottom, right, top) rectangle in normalized figure
+ coordinates that the whole subplots area (including labels) will
+ fit into. Default (None) is the whole figure.
+ """
+ if renderer is None:
+ renderer = figure._get_renderer()
+ kwargs = _tight_layout.get_tight_layout_figure(
+ figure, figure.axes,
+ _tight_layout.get_subplotspec_list(figure.axes, grid_spec=self),
+ renderer, pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
+ if kwargs:
+ self.update(**kwargs)
+
+
+class GridSpecFromSubplotSpec(GridSpecBase):
+ """
+ GridSpec whose subplot layout parameters are inherited from the
+ location specified by a given SubplotSpec.
+ """
+ def __init__(self, nrows, ncols,
+ subplot_spec,
+ wspace=None, hspace=None,
+ height_ratios=None, width_ratios=None):
+ """
+ Parameters
+ ----------
+ nrows, ncols : int
+ Number of rows and number of columns of the grid.
+ subplot_spec : SubplotSpec
+ Spec from which the layout parameters are inherited.
+ wspace, hspace : float, optional
+ See `GridSpec` for more details. If not specified default values
+ (from the figure or rcParams) are used.
+ height_ratios : array-like of length *nrows*, optional
+ See `GridSpecBase` for details.
+ width_ratios : array-like of length *ncols*, optional
+ See `GridSpecBase` for details.
+ """
+ self._wspace = wspace
+ self._hspace = hspace
+ self._subplot_spec = subplot_spec
+ self.figure = self._subplot_spec.get_gridspec().figure
+ super().__init__(nrows, ncols,
+ width_ratios=width_ratios,
+ height_ratios=height_ratios)
+
+ 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 mpl.rcParams["figure.subplot.hspace"])
+ wspace = (self._wspace if self._wspace is not None
+ else figure.subplotpars.wspace if figure is not None
+ else mpl.rcParams["figure.subplot.wspace"])
+
+ figbox = self._subplot_spec.get_position(figure)
+ left, bottom, right, top = figbox.extents
+
+ return mpl.figure.SubplotParams(left=left, right=right,
+ bottom=bottom, top=top,
+ wspace=wspace, hspace=hspace)
+
+ def get_topmost_subplotspec(self):
+ """
+ Return the topmost `.SubplotSpec` instance associated with the subplot.
+ """
+ return self._subplot_spec.get_topmost_subplotspec()
+
+
+class SubplotSpec:
+ """
+ The location of a subplot in a `GridSpec`.
+
+ .. note::
+
+ Likely, you will never instantiate a `SubplotSpec` yourself. Instead,
+ you will typically obtain one from a `GridSpec` using item-access.
+
+ Parameters
+ ----------
+ gridspec : `~matplotlib.gridspec.GridSpec`
+ The GridSpec, which the subplot is referencing.
+ num1, num2 : int
+ The subplot will occupy the *num1*-th cell of the given
+ *gridspec*. If *num2* is provided, the subplot will span between
+ *num1*-th cell and *num2*-th cell **inclusive**.
+
+ The index starts from 0.
+ """
+ def __init__(self, gridspec, num1, num2=None):
+ self._gridspec = gridspec
+ self.num1 = num1
+ self.num2 = num2
+
+ def __repr__(self):
+ return (f"{self.get_gridspec()}["
+ f"{self.rowspan.start}:{self.rowspan.stop}, "
+ f"{self.colspan.start}:{self.colspan.stop}]")
+
+ @staticmethod
+ def _from_subplot_args(figure, args):
+ """
+ Construct a `.SubplotSpec` from a parent `.Figure` and either
+
+ - a `.SubplotSpec` -- returned as is;
+ - one or three numbers -- a MATLAB-style subplot specifier.
+ """
+ if len(args) == 1:
+ arg, = args
+ if isinstance(arg, SubplotSpec):
+ return arg
+ elif not isinstance(arg, Integral):
+ raise ValueError(
+ f"Single argument to subplot must be a three-digit "
+ f"integer, not {arg!r}")
+ try:
+ rows, cols, num = map(int, str(arg))
+ except ValueError:
+ raise ValueError(
+ f"Single argument to subplot must be a three-digit "
+ f"integer, not {arg!r}") from None
+ elif len(args) == 3:
+ rows, cols, num = args
+ else:
+ raise _api.nargs_error("subplot", takes="1 or 3", given=len(args))
+
+ gs = GridSpec._check_gridspec_exists(figure, rows, cols)
+ if gs is None:
+ gs = GridSpec(rows, cols, figure=figure)
+ if isinstance(num, tuple) and len(num) == 2:
+ if not all(isinstance(n, Integral) for n in num):
+ raise ValueError(
+ f"Subplot specifier tuple must contain integers, not {num}"
+ )
+ i, j = num
+ else:
+ if not isinstance(num, Integral) or num < 1 or num > rows*cols:
+ raise ValueError(
+ f"num must be an integer with 1 <= num <= {rows*cols}, "
+ f"not {num!r}"
+ )
+ i = j = num
+ return gs[i-1:j]
+
+ # num2 is a property only to handle the case where it is None and someone
+ # mutates num1.
+
+ @property
+ def num2(self):
+ return self.num1 if self._num2 is None else self._num2
+
+ @num2.setter
+ def num2(self, value):
+ self._num2 = value
+
+ def get_gridspec(self):
+ return self._gridspec
+
+ def get_geometry(self):
+ """
+ Return the subplot geometry as tuple ``(n_rows, n_cols, start, stop)``.
+
+ The indices *start* and *stop* define the range of the subplot within
+ the `GridSpec`. *stop* is inclusive (i.e. for a single cell
+ ``start == stop``).
+ """
+ rows, cols = self.get_gridspec().get_geometry()
+ return rows, cols, self.num1, self.num2
+
+ @property
+ def rowspan(self):
+ """The rows spanned by this subplot, as a `range` object."""
+ ncols = self.get_gridspec().ncols
+ return range(self.num1 // ncols, self.num2 // ncols + 1)
+
+ @property
+ def colspan(self):
+ """The columns spanned by this subplot, as a `range` object."""
+ ncols = self.get_gridspec().ncols
+ # We explicitly support num2 referring to a column on num1's *left*, so
+ # we must sort the column indices here so that the range makes sense.
+ c1, c2 = sorted([self.num1 % ncols, self.num2 % ncols])
+ return range(c1, c2 + 1)
+
+ def is_first_row(self):
+ return self.rowspan.start == 0
+
+ def is_last_row(self):
+ return self.rowspan.stop == self.get_gridspec().nrows
+
+ def is_first_col(self):
+ return self.colspan.start == 0
+
+ def is_last_col(self):
+ return self.colspan.stop == self.get_gridspec().ncols
+
+ def get_position(self, figure):
+ """
+ Update the subplot position from ``figure.subplotpars``.
+ """
+ gridspec = self.get_gridspec()
+ nrows, ncols = gridspec.get_geometry()
+ rows, cols = np.unravel_index([self.num1, self.num2], (nrows, ncols))
+ fig_bottoms, fig_tops, fig_lefts, fig_rights = \
+ gridspec.get_grid_positions(figure)
+
+ fig_bottom = fig_bottoms[rows].min()
+ fig_top = fig_tops[rows].max()
+ fig_left = fig_lefts[cols].min()
+ fig_right = fig_rights[cols].max()
+ return Bbox.from_extents(fig_left, fig_bottom, fig_right, fig_top)
+
+ def get_topmost_subplotspec(self):
+ """
+ Return the topmost `SubplotSpec` instance associated with the subplot.
+ """
+ gridspec = self.get_gridspec()
+ if hasattr(gridspec, "get_topmost_subplotspec"):
+ return gridspec.get_topmost_subplotspec()
+ else:
+ return self
+
+ def __eq__(self, other):
+ """
+ Two SubplotSpecs are considered equal if they refer to the same
+ position(s) in the same `GridSpec`.
+ """
+ # other may not even have the attributes we are checking.
+ return ((self._gridspec, self.num1, self.num2)
+ == (getattr(other, "_gridspec", object()),
+ getattr(other, "num1", object()),
+ getattr(other, "num2", object())))
+
+ def __hash__(self):
+ return hash((self._gridspec, self.num1, self.num2))
+
+ def subgridspec(self, nrows, ncols, **kwargs):
+ """
+ Create a GridSpec within this subplot.
+
+ The created `.GridSpecFromSubplotSpec` will have this `SubplotSpec` as
+ a parent.
+
+ Parameters
+ ----------
+ nrows : int
+ Number of rows in grid.
+
+ ncols : int
+ Number of columns in grid.
+
+ Returns
+ -------
+ `.GridSpecFromSubplotSpec`
+
+ Other Parameters
+ ----------------
+ **kwargs
+ All other parameters are passed to `.GridSpecFromSubplotSpec`.
+
+ See Also
+ --------
+ matplotlib.pyplot.subplots
+
+ Examples
+ --------
+ Adding three subplots in the space occupied by a single subplot::
+
+ fig = plt.figure()
+ gs0 = fig.add_gridspec(3, 1)
+ ax1 = fig.add_subplot(gs0[0])
+ ax2 = fig.add_subplot(gs0[1])
+ gssub = gs0[2].subgridspec(1, 3)
+ for i in range(3):
+ fig.add_subplot(gssub[0, i])
+ """
+ return GridSpecFromSubplotSpec(nrows, ncols, self, **kwargs)
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/layout_engine.py b/omnilmm/lib/python3.10/site-packages/matplotlib/layout_engine.py
new file mode 100644
index 0000000000000000000000000000000000000000..953909d12e94fb0e3e2d3249d6a5228b4290f7f5
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/layout_engine.py
@@ -0,0 +1,305 @@
+"""
+Classes to layout elements in a `.Figure`.
+
+Figures have a ``layout_engine`` property that holds a subclass of
+`~.LayoutEngine` defined here (or *None* for no layout). At draw time
+``figure.get_layout_engine().execute()`` is called, the goal of which is
+usually to rearrange Axes on the figure to produce a pleasing layout. This is
+like a ``draw`` callback but with two differences. First, when printing we
+disable the layout engine for the final draw. Second, it is useful to know the
+layout engine while the figure is being created. In particular, colorbars are
+made differently with different layout engines (for historical reasons).
+
+Matplotlib supplies two layout engines, `.TightLayoutEngine` and
+`.ConstrainedLayoutEngine`. Third parties can create their own layout engine
+by subclassing `.LayoutEngine`.
+"""
+
+from contextlib import nullcontext
+
+import matplotlib as mpl
+
+from matplotlib._constrained_layout import do_constrained_layout
+from matplotlib._tight_layout import (get_subplotspec_list,
+ get_tight_layout_figure)
+
+
+class LayoutEngine:
+ """
+ Base class for Matplotlib layout engines.
+
+ A layout engine can be passed to a figure at instantiation or at any time
+ with `~.figure.Figure.set_layout_engine`. Once attached to a figure, the
+ layout engine ``execute`` function is called at draw time by
+ `~.figure.Figure.draw`, providing a special draw-time hook.
+
+ .. note::
+
+ However, note that layout engines affect the creation of colorbars, so
+ `~.figure.Figure.set_layout_engine` should be called before any
+ colorbars are created.
+
+ Currently, there are two properties of `LayoutEngine` classes that are
+ consulted while manipulating the figure:
+
+ - ``engine.colorbar_gridspec`` tells `.Figure.colorbar` whether to make the
+ axes using the gridspec method (see `.colorbar.make_axes_gridspec`) or
+ not (see `.colorbar.make_axes`);
+ - ``engine.adjust_compatible`` stops `.Figure.subplots_adjust` from being
+ run if it is not compatible with the layout engine.
+
+ To implement a custom `LayoutEngine`:
+
+ 1. override ``_adjust_compatible`` and ``_colorbar_gridspec``
+ 2. override `LayoutEngine.set` to update *self._params*
+ 3. override `LayoutEngine.execute` with your implementation
+
+ """
+ # override these in subclass
+ _adjust_compatible = None
+ _colorbar_gridspec = None
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self._params = {}
+
+ def set(self, **kwargs):
+ """
+ Set the parameters for the layout engine.
+ """
+ raise NotImplementedError
+
+ @property
+ def colorbar_gridspec(self):
+ """
+ Return a boolean if the layout engine creates colorbars using a
+ gridspec.
+ """
+ if self._colorbar_gridspec is None:
+ raise NotImplementedError
+ return self._colorbar_gridspec
+
+ @property
+ def adjust_compatible(self):
+ """
+ Return a boolean if the layout engine is compatible with
+ `~.Figure.subplots_adjust`.
+ """
+ if self._adjust_compatible is None:
+ raise NotImplementedError
+ return self._adjust_compatible
+
+ def get(self):
+ """
+ Return copy of the parameters for the layout engine.
+ """
+ return dict(self._params)
+
+ def execute(self, fig):
+ """
+ Execute the layout on the figure given by *fig*.
+ """
+ # subclasses must implement this.
+ raise NotImplementedError
+
+
+class PlaceHolderLayoutEngine(LayoutEngine):
+ """
+ This layout engine does not adjust the figure layout at all.
+
+ The purpose of this `.LayoutEngine` is to act as a placeholder when the
+ user removes a layout engine to ensure an incompatible `.LayoutEngine` can
+ not be set later.
+
+ Parameters
+ ----------
+ adjust_compatible, colorbar_gridspec : bool
+ Allow the PlaceHolderLayoutEngine to mirror the behavior of whatever
+ layout engine it is replacing.
+
+ """
+ def __init__(self, adjust_compatible, colorbar_gridspec, **kwargs):
+ self._adjust_compatible = adjust_compatible
+ self._colorbar_gridspec = colorbar_gridspec
+ super().__init__(**kwargs)
+
+ def execute(self, fig):
+ """
+ Do nothing.
+ """
+ return
+
+
+class TightLayoutEngine(LayoutEngine):
+ """
+ Implements the ``tight_layout`` geometry management. See
+ :doc:`/tutorials/intermediate/tight_layout_guide` for details.
+ """
+ _adjust_compatible = True
+ _colorbar_gridspec = True
+
+ def __init__(self, *, pad=1.08, h_pad=None, w_pad=None,
+ rect=(0, 0, 1, 1), **kwargs):
+ """
+ Initialize tight_layout engine.
+
+ Parameters
+ ----------
+ pad : float, default: 1.08
+ Padding between the figure edge and the edges of subplots, as a
+ fraction of the font size.
+ h_pad, w_pad : float
+ Padding (height/width) between edges of adjacent subplots.
+ Defaults to *pad*.
+ rect : tuple (left, bottom, right, top), default: (0, 0, 1, 1).
+ rectangle in normalized figure coordinates that the subplots
+ (including labels) will fit into.
+ """
+ super().__init__(**kwargs)
+ for td in ['pad', 'h_pad', 'w_pad', 'rect']:
+ # initialize these in case None is passed in above:
+ self._params[td] = None
+ self.set(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
+
+ def execute(self, fig):
+ """
+ Execute tight_layout.
+
+ This decides the subplot parameters given the padding that
+ will allow the axes labels to not be covered by other labels
+ and axes.
+
+ Parameters
+ ----------
+ fig : `.Figure` to perform layout on.
+
+ See Also
+ --------
+ .figure.Figure.tight_layout
+ .pyplot.tight_layout
+ """
+ info = self._params
+ renderer = fig._get_renderer()
+ with getattr(renderer, "_draw_disabled", nullcontext)():
+ kwargs = get_tight_layout_figure(
+ fig, fig.axes, get_subplotspec_list(fig.axes), renderer,
+ pad=info['pad'], h_pad=info['h_pad'], w_pad=info['w_pad'],
+ rect=info['rect'])
+ if kwargs:
+ fig.subplots_adjust(**kwargs)
+
+ def set(self, *, pad=None, w_pad=None, h_pad=None, rect=None):
+ """
+ Set the pads for tight_layout.
+
+ Parameters
+ ----------
+ pad : float
+ Padding between the figure edge and the edges of subplots, as a
+ fraction of the font size.
+ w_pad, h_pad : float
+ Padding (width/height) between edges of adjacent subplots.
+ Defaults to *pad*.
+ rect : tuple (left, bottom, right, top)
+ rectangle in normalized figure coordinates that the subplots
+ (including labels) will fit into.
+ """
+ for td in self.set.__kwdefaults__:
+ if locals()[td] is not None:
+ self._params[td] = locals()[td]
+
+
+class ConstrainedLayoutEngine(LayoutEngine):
+ """
+ Implements the ``constrained_layout`` geometry management. See
+ :doc:`/tutorials/intermediate/constrainedlayout_guide` for details.
+ """
+
+ _adjust_compatible = False
+ _colorbar_gridspec = False
+
+ def __init__(self, *, h_pad=None, w_pad=None,
+ hspace=None, wspace=None, rect=(0, 0, 1, 1),
+ compress=False, **kwargs):
+ """
+ Initialize ``constrained_layout`` settings.
+
+ Parameters
+ ----------
+ h_pad, w_pad : float
+ Padding around the axes elements in figure-normalized units.
+ Default to :rc:`figure.constrained_layout.h_pad` and
+ :rc:`figure.constrained_layout.w_pad`.
+ hspace, wspace : float
+ Fraction of the figure to dedicate to space between the
+ axes. These are evenly spread between the gaps between the axes.
+ A value of 0.2 for a three-column layout would have a space
+ of 0.1 of the figure width between each column.
+ If h/wspace < h/w_pad, then the pads are used instead.
+ Default to :rc:`figure.constrained_layout.hspace` and
+ :rc:`figure.constrained_layout.wspace`.
+ rect : tuple of 4 floats
+ Rectangle in figure coordinates to perform constrained layout in
+ (left, bottom, width, height), each from 0-1.
+ compress : bool
+ Whether to shift Axes so that white space in between them is
+ removed. This is useful for simple grids of fixed-aspect Axes (e.g.
+ a grid of images). See :ref:`compressed_layout`.
+ """
+ super().__init__(**kwargs)
+ # set the defaults:
+ self.set(w_pad=mpl.rcParams['figure.constrained_layout.w_pad'],
+ h_pad=mpl.rcParams['figure.constrained_layout.h_pad'],
+ wspace=mpl.rcParams['figure.constrained_layout.wspace'],
+ hspace=mpl.rcParams['figure.constrained_layout.hspace'],
+ rect=(0, 0, 1, 1))
+ # set anything that was passed in (None will be ignored):
+ self.set(w_pad=w_pad, h_pad=h_pad, wspace=wspace, hspace=hspace,
+ rect=rect)
+ self._compress = compress
+
+ def execute(self, fig):
+ """
+ Perform constrained_layout and move and resize axes accordingly.
+
+ Parameters
+ ----------
+ fig : `.Figure` to perform layout on.
+ """
+ width, height = fig.get_size_inches()
+ # pads are relative to the current state of the figure...
+ w_pad = self._params['w_pad'] / width
+ h_pad = self._params['h_pad'] / height
+
+ return do_constrained_layout(fig, w_pad=w_pad, h_pad=h_pad,
+ wspace=self._params['wspace'],
+ hspace=self._params['hspace'],
+ rect=self._params['rect'],
+ compress=self._compress)
+
+ def set(self, *, h_pad=None, w_pad=None,
+ hspace=None, wspace=None, rect=None):
+ """
+ Set the pads for constrained_layout.
+
+ Parameters
+ ----------
+ h_pad, w_pad : float
+ Padding around the axes elements in figure-normalized units.
+ Default to :rc:`figure.constrained_layout.h_pad` and
+ :rc:`figure.constrained_layout.w_pad`.
+ hspace, wspace : float
+ Fraction of the figure to dedicate to space between the
+ axes. These are evenly spread between the gaps between the axes.
+ A value of 0.2 for a three-column layout would have a space
+ of 0.1 of the figure width between each column.
+ If h/wspace < h/w_pad, then the pads are used instead.
+ Default to :rc:`figure.constrained_layout.hspace` and
+ :rc:`figure.constrained_layout.wspace`.
+ rect : tuple of 4 floats
+ Rectangle in figure coordinates to perform constrained layout in
+ (left, bottom, width, height), each from 0-1.
+ """
+ for td in self.set.__kwdefaults__:
+ if locals()[td] is not None:
+ self._params[td] = locals()[td]
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/legend.py b/omnilmm/lib/python3.10/site-packages/matplotlib/legend.py
new file mode 100644
index 0000000000000000000000000000000000000000..78ea22a7ebdc04b905915a85dfdc082fdb8c12d4
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/legend.py
@@ -0,0 +1,1348 @@
+"""
+The legend module defines the Legend class, which is responsible for
+drawing legends associated with axes and/or figures.
+
+.. important::
+
+ It is unlikely that you would ever create a Legend instance manually.
+ Most users would normally create a legend via the `~.Axes.legend`
+ function. For more details on legends there is also a :doc:`legend guide
+ `.
+
+The `Legend` class is a container of legend handles and legend texts.
+
+The legend handler map specifies how to create legend handles from artists
+(lines, patches, etc.) in the axes or figures. Default legend handlers are
+defined in the :mod:`~matplotlib.legend_handler` module. While not all artist
+types are covered by the default legend handlers, custom legend handlers can be
+defined to support arbitrary objects.
+
+See the :doc:`legend guide ` for more
+information.
+"""
+
+import itertools
+import logging
+import time
+
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib import _api, _docstring, colors, offsetbox
+from matplotlib.artist import Artist, allow_rasterization
+from matplotlib.cbook import silent_list
+from matplotlib.font_manager import FontProperties
+from matplotlib.lines import Line2D
+from matplotlib.patches import (Patch, Rectangle, Shadow, FancyBboxPatch,
+ StepPatch)
+from matplotlib.collections import (
+ Collection, CircleCollection, LineCollection, PathCollection,
+ PolyCollection, RegularPolyCollection)
+from matplotlib.text import Text
+from matplotlib.transforms import Bbox, BboxBase, TransformedBbox
+from matplotlib.transforms import BboxTransformTo, BboxTransformFrom
+from matplotlib.offsetbox import (
+ AnchoredOffsetbox, DraggableOffsetBox,
+ HPacker, VPacker,
+ DrawingArea, TextArea,
+)
+from matplotlib.container import ErrorbarContainer, BarContainer, StemContainer
+from . import legend_handler
+
+
+class DraggableLegend(DraggableOffsetBox):
+ def __init__(self, legend, use_blit=False, update="loc"):
+ """
+ Wrapper around a `.Legend` to support mouse dragging.
+
+ Parameters
+ ----------
+ legend : `.Legend`
+ The `.Legend` instance to wrap.
+ use_blit : bool, optional
+ Use blitting for faster image composition. For details see
+ :ref:`func-animation`.
+ update : {'loc', 'bbox'}, optional
+ If "loc", update the *loc* parameter of the legend upon finalizing.
+ If "bbox", update the *bbox_to_anchor* parameter.
+ """
+ self.legend = legend
+
+ _api.check_in_list(["loc", "bbox"], update=update)
+ self._update = update
+
+ super().__init__(legend, legend._legend_box, use_blit=use_blit)
+
+ def finalize_offset(self):
+ if self._update == "loc":
+ self._update_loc(self.get_loc_in_canvas())
+ elif self._update == "bbox":
+ self._update_bbox_to_anchor(self.get_loc_in_canvas())
+
+ def _update_loc(self, loc_in_canvas):
+ bbox = self.legend.get_bbox_to_anchor()
+ # if bbox has zero width or height, the transformation is
+ # ill-defined. Fall back to the default bbox_to_anchor.
+ if bbox.width == 0 or bbox.height == 0:
+ self.legend.set_bbox_to_anchor(None)
+ bbox = self.legend.get_bbox_to_anchor()
+ _bbox_transform = BboxTransformFrom(bbox)
+ self.legend._loc = tuple(_bbox_transform.transform(loc_in_canvas))
+
+ def _update_bbox_to_anchor(self, loc_in_canvas):
+ loc_in_bbox = self.legend.axes.transAxes.transform(loc_in_canvas)
+ self.legend.set_bbox_to_anchor(loc_in_bbox)
+
+
+_legend_kw_doc_base = """
+bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats
+ Box that is used to position the legend in conjunction with *loc*.
+ Defaults to `axes.bbox` (if called as a method to `.Axes.legend`) or
+ `figure.bbox` (if `.Figure.legend`). This argument allows arbitrary
+ placement of the legend.
+
+ Bbox coordinates are interpreted in the coordinate system given by
+ *bbox_transform*, with the default transform
+ Axes or Figure coordinates, depending on which ``legend`` is called.
+
+ If a 4-tuple or `.BboxBase` is given, then it specifies the bbox
+ ``(x, y, width, height)`` that the legend is placed in.
+ To put the legend in the best location in the bottom right
+ quadrant of the axes (or figure)::
+
+ loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
+
+ A 2-tuple ``(x, y)`` places the corner of the legend specified by *loc* at
+ x, y. For example, to put the legend's upper right-hand corner in the
+ center of the axes (or figure) the following keywords can be used::
+
+ loc='upper right', bbox_to_anchor=(0.5, 0.5)
+
+ncols : int, default: 1
+ The number of columns that the legend has.
+
+ For backward compatibility, the spelling *ncol* is also supported
+ but it is discouraged. If both are given, *ncols* takes precedence.
+
+prop : None or `~matplotlib.font_manager.FontProperties` or dict
+ The font properties of the legend. If None (default), the current
+ :data:`matplotlib.rcParams` will be used.
+
+fontsize : int or {'xx-small', 'x-small', 'small', 'medium', 'large', \
+'x-large', 'xx-large'}
+ The font size of the legend. If the value is numeric the size will be the
+ absolute font size in points. String values are relative to the current
+ default font size. This argument is only used if *prop* is not specified.
+
+labelcolor : str or list, default: :rc:`legend.labelcolor`
+ The color of the text in the legend. Either a valid color string
+ (for example, 'red'), or a list of color strings. The labelcolor can
+ also be made to match the color of the line or marker using 'linecolor',
+ 'markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec').
+
+ Labelcolor can be set globally using :rc:`legend.labelcolor`. If None,
+ use :rc:`text.color`.
+
+numpoints : int, default: :rc:`legend.numpoints`
+ The number of marker points in the legend when creating a legend
+ entry for a `.Line2D` (line).
+
+scatterpoints : int, default: :rc:`legend.scatterpoints`
+ The number of marker points in the legend when creating
+ a legend entry for a `.PathCollection` (scatter plot).
+
+scatteryoffsets : iterable of floats, default: ``[0.375, 0.5, 0.3125]``
+ The vertical offset (relative to the font size) for the markers
+ created for a scatter plot legend entry. 0.0 is at the base the
+ legend text, and 1.0 is at the top. To draw all markers at the
+ same height, set to ``[0.5]``.
+
+markerscale : float, default: :rc:`legend.markerscale`
+ The relative size of legend markers compared to the originally drawn ones.
+
+markerfirst : bool, default: True
+ If *True*, legend marker is placed to the left of the legend label.
+ If *False*, legend marker is placed to the right of the legend label.
+
+reverse : bool, default: False
+ If *True*, the legend labels are displayed in reverse order from the input.
+ If *False*, the legend labels are displayed in the same order as the input.
+
+ .. versionadded:: 3.7
+
+frameon : bool, default: :rc:`legend.frameon`
+ Whether the legend should be drawn on a patch (frame).
+
+fancybox : bool, default: :rc:`legend.fancybox`
+ Whether round edges should be enabled around the `.FancyBboxPatch` which
+ makes up the legend's background.
+
+shadow : bool, default: :rc:`legend.shadow`
+ Whether to draw a shadow behind the legend.
+
+framealpha : float, default: :rc:`legend.framealpha`
+ The alpha transparency of the legend's background.
+ If *shadow* is activated and *framealpha* is ``None``, the default value is
+ ignored.
+
+facecolor : "inherit" or color, default: :rc:`legend.facecolor`
+ The legend's background color.
+ If ``"inherit"``, use :rc:`axes.facecolor`.
+
+edgecolor : "inherit" or color, default: :rc:`legend.edgecolor`
+ The legend's background patch edge color.
+ If ``"inherit"``, use take :rc:`axes.edgecolor`.
+
+mode : {"expand", None}
+ If *mode* is set to ``"expand"`` the legend will be horizontally
+ expanded to fill the axes area (or *bbox_to_anchor* if defines
+ the legend's size).
+
+bbox_transform : None or `~matplotlib.transforms.Transform`
+ The transform for the bounding box (*bbox_to_anchor*). For a value
+ of ``None`` (default) the Axes'
+ :data:`~matplotlib.axes.Axes.transAxes` transform will be used.
+
+title : str or None
+ The legend's title. Default is no title (``None``).
+
+title_fontproperties : None or `~matplotlib.font_manager.FontProperties` or dict
+ The font properties of the legend's title. If None (default), the
+ *title_fontsize* argument will be used if present; if *title_fontsize* is
+ also None, the current :rc:`legend.title_fontsize` will be used.
+
+title_fontsize : int or {'xx-small', 'x-small', 'small', 'medium', 'large', \
+'x-large', 'xx-large'}, default: :rc:`legend.title_fontsize`
+ The font size of the legend's title.
+ Note: This cannot be combined with *title_fontproperties*. If you want
+ to set the fontsize alongside other font properties, use the *size*
+ parameter in *title_fontproperties*.
+
+alignment : {'center', 'left', 'right'}, default: 'center'
+ The alignment of the legend title and the box of entries. The entries
+ are aligned as a single block, so that markers always lined up.
+
+borderpad : float, default: :rc:`legend.borderpad`
+ The fractional whitespace inside the legend border, in font-size units.
+
+labelspacing : float, default: :rc:`legend.labelspacing`
+ The vertical space between the legend entries, in font-size units.
+
+handlelength : float, default: :rc:`legend.handlelength`
+ The length of the legend handles, in font-size units.
+
+handleheight : float, default: :rc:`legend.handleheight`
+ The height of the legend handles, in font-size units.
+
+handletextpad : float, default: :rc:`legend.handletextpad`
+ The pad between the legend handle and text, in font-size units.
+
+borderaxespad : float, default: :rc:`legend.borderaxespad`
+ The pad between the axes and legend border, in font-size units.
+
+columnspacing : float, default: :rc:`legend.columnspacing`
+ The spacing between columns, in font-size units.
+
+handler_map : dict or None
+ The custom dictionary mapping instances or types to a legend
+ handler. This *handler_map* updates the default handler map
+ found at `matplotlib.legend.Legend.get_legend_handler_map`.
+
+draggable : bool, default: False
+ Whether the legend can be dragged with the mouse.
+"""
+
+_loc_doc_base = """
+loc : str or pair of floats, default: {default}
+ The location of the legend.
+
+ The strings ``'upper left'``, ``'upper right'``, ``'lower left'``,
+ ``'lower right'`` place the legend at the corresponding corner of the
+ {parent}.
+
+ The strings ``'upper center'``, ``'lower center'``, ``'center left'``,
+ ``'center right'`` place the legend at the center of the corresponding edge
+ of the {parent}.
+
+ The string ``'center'`` places the legend at the center of the {parent}.
+{best}
+ The location can also be a 2-tuple giving the coordinates of the lower-left
+ corner of the legend in {parent} coordinates (in which case *bbox_to_anchor*
+ will be ignored).
+
+ For back-compatibility, ``'center right'`` (but no other location) can also
+ be spelled ``'right'``, and each "string" location can also be given as a
+ numeric value:
+
+ ================== =============
+ Location String Location Code
+ ================== =============
+ 'best' (Axes only) 0
+ 'upper right' 1
+ 'upper left' 2
+ 'lower left' 3
+ 'lower right' 4
+ 'right' 5
+ 'center left' 6
+ 'center right' 7
+ 'lower center' 8
+ 'upper center' 9
+ 'center' 10
+ ================== =============
+ {outside}"""
+
+_loc_doc_best = """
+ The string ``'best'`` places the legend at the location, among the nine
+ locations defined so far, with the minimum overlap with other drawn
+ artists. This option can be quite slow for plots with large amounts of
+ data; your plotting speed may benefit from providing a specific location.
+"""
+
+_legend_kw_axes_st = (
+ _loc_doc_base.format(parent='axes', default=':rc:`legend.loc`',
+ best=_loc_doc_best, outside='') +
+ _legend_kw_doc_base)
+_docstring.interpd.update(_legend_kw_axes=_legend_kw_axes_st)
+
+_outside_doc = """
+ If a figure is using the constrained layout manager, the string codes
+ of the *loc* keyword argument can get better layout behaviour using the
+ prefix 'outside'. There is ambiguity at the corners, so 'outside
+ upper right' will make space for the legend above the rest of the
+ axes in the layout, and 'outside right upper' will make space on the
+ right side of the layout. In addition to the values of *loc*
+ listed above, we have 'outside right upper', 'outside right lower',
+ 'outside left upper', and 'outside left lower'. See
+ :doc:`/tutorials/intermediate/legend_guide` for more details.
+"""
+
+_legend_kw_figure_st = (
+ _loc_doc_base.format(parent='figure', default="'upper right'",
+ best='', outside=_outside_doc) +
+ _legend_kw_doc_base)
+_docstring.interpd.update(_legend_kw_figure=_legend_kw_figure_st)
+
+_legend_kw_both_st = (
+ _loc_doc_base.format(parent='axes/figure',
+ default=":rc:`legend.loc` for Axes, 'upper right' for Figure",
+ best=_loc_doc_best, outside=_outside_doc) +
+ _legend_kw_doc_base)
+_docstring.interpd.update(_legend_kw_doc=_legend_kw_both_st)
+
+
+class Legend(Artist):
+ """
+ Place a legend on the figure/axes.
+ """
+
+ # 'best' is only implemented for axes legends
+ codes = {'best': 0, **AnchoredOffsetbox.codes}
+ zorder = 5
+
+ def __str__(self):
+ return "Legend"
+
+ @_api.make_keyword_only("3.6", "loc")
+ @_docstring.dedent_interpd
+ def __init__(
+ self, parent, handles, labels,
+ loc=None,
+ numpoints=None, # number of points in the legend line
+ markerscale=None, # relative size of legend markers vs. original
+ markerfirst=True, # left/right ordering of legend marker and label
+ reverse=False, # reverse ordering of legend marker and label
+ scatterpoints=None, # number of scatter points
+ scatteryoffsets=None,
+ prop=None, # properties for the legend texts
+ fontsize=None, # keyword to set font size directly
+ labelcolor=None, # keyword to set the text color
+
+ # spacing & pad defined as a fraction of the font-size
+ borderpad=None, # whitespace inside the legend border
+ labelspacing=None, # vertical space between the legend entries
+ handlelength=None, # length of the legend handles
+ handleheight=None, # height of the legend handles
+ handletextpad=None, # pad between the legend handle and text
+ borderaxespad=None, # pad between the axes and legend border
+ columnspacing=None, # spacing between columns
+
+ ncols=1, # number of columns
+ mode=None, # horizontal distribution of columns: None or "expand"
+
+ fancybox=None, # True: fancy box, False: rounded box, None: rcParam
+ shadow=None,
+ title=None, # legend title
+ title_fontsize=None, # legend title font size
+ framealpha=None, # set frame alpha
+ edgecolor=None, # frame patch edgecolor
+ facecolor=None, # frame patch facecolor
+
+ bbox_to_anchor=None, # bbox to which the legend will be anchored
+ bbox_transform=None, # transform for the bbox
+ frameon=None, # draw frame
+ handler_map=None,
+ title_fontproperties=None, # properties for the legend title
+ alignment="center", # control the alignment within the legend box
+ *,
+ ncol=1, # synonym for ncols (backward compatibility)
+ draggable=False # whether the legend can be dragged with the mouse
+ ):
+ """
+ Parameters
+ ----------
+ parent : `~matplotlib.axes.Axes` or `.Figure`
+ The artist that contains the legend.
+
+ handles : list of `.Artist`
+ A list of Artists (lines, patches) to be added to the legend.
+
+ labels : list of str
+ A list of labels to show next to the artists. The length of handles
+ and labels should be the same. If they are not, they are truncated
+ to the length of the shorter list.
+
+ Other Parameters
+ ----------------
+ %(_legend_kw_doc)s
+
+ Attributes
+ ----------
+ legend_handles
+ List of `.Artist` objects added as legend entries.
+
+ .. versionadded:: 3.7
+ """
+ # local import only to avoid circularity
+ from matplotlib.axes import Axes
+ from matplotlib.figure import FigureBase
+
+ super().__init__()
+
+ if prop is None:
+ if fontsize is not None:
+ self.prop = FontProperties(size=fontsize)
+ else:
+ 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(mpl.rcParams["legend.fontsize"])
+
+ self._fontsize = self.prop.get_size_in_points()
+
+ self.texts = []
+ self.legend_handles = []
+ self._legend_title_box = None
+
+ #: A dictionary with the extra handler mappings for this Legend
+ #: instance.
+ self._custom_handler_map = handler_map
+
+ def val_or_rc(val, rc_name):
+ return val if val is not None else mpl.rcParams[rc_name]
+
+ self.numpoints = val_or_rc(numpoints, 'legend.numpoints')
+ self.markerscale = val_or_rc(markerscale, 'legend.markerscale')
+ self.scatterpoints = val_or_rc(scatterpoints, 'legend.scatterpoints')
+ self.borderpad = val_or_rc(borderpad, 'legend.borderpad')
+ self.labelspacing = val_or_rc(labelspacing, 'legend.labelspacing')
+ self.handlelength = val_or_rc(handlelength, 'legend.handlelength')
+ self.handleheight = val_or_rc(handleheight, 'legend.handleheight')
+ self.handletextpad = val_or_rc(handletextpad, 'legend.handletextpad')
+ self.borderaxespad = val_or_rc(borderaxespad, 'legend.borderaxespad')
+ self.columnspacing = val_or_rc(columnspacing, 'legend.columnspacing')
+ self.shadow = val_or_rc(shadow, 'legend.shadow')
+ # trim handles and labels if illegal label...
+ _lab, _hand = [], []
+ for label, handle in zip(labels, handles):
+ if isinstance(label, str) and label.startswith('_'):
+ _api.warn_external(f"The label {label!r} of {handle!r} starts "
+ "with '_'. It is thus excluded from the "
+ "legend.")
+ else:
+ _lab.append(label)
+ _hand.append(handle)
+ labels, handles = _lab, _hand
+
+ if reverse:
+ labels.reverse()
+ handles.reverse()
+
+ if len(handles) < 2:
+ ncols = 1
+ self._ncols = ncols if ncols != 1 else ncol
+
+ if self.numpoints <= 0:
+ raise ValueError("numpoints must be > 0; it was %d" % numpoints)
+
+ # introduce y-offset for handles of the scatter plot
+ if scatteryoffsets is None:
+ self._scatteryoffsets = np.array([3. / 8., 4. / 8., 2.5 / 8.])
+ else:
+ self._scatteryoffsets = np.asarray(scatteryoffsets)
+ reps = self.scatterpoints // len(self._scatteryoffsets) + 1
+ self._scatteryoffsets = np.tile(self._scatteryoffsets,
+ reps)[:self.scatterpoints]
+
+ # _legend_box is a VPacker instance that contains all
+ # legend items and will be initialized from _init_legend_box()
+ # method.
+ self._legend_box = None
+
+ if isinstance(parent, Axes):
+ self.isaxes = True
+ self.axes = parent
+ self.set_figure(parent.figure)
+ elif isinstance(parent, FigureBase):
+ self.isaxes = False
+ self.set_figure(parent)
+ else:
+ raise TypeError(
+ "Legend needs either Axes or FigureBase as parent"
+ )
+ self.parent = parent
+
+ loc0 = loc
+ self._loc_used_default = loc is None
+ if loc is None:
+ loc = mpl.rcParams["legend.loc"]
+ if not self.isaxes and loc in [0, 'best']:
+ loc = 'upper right'
+
+ # handle outside legends:
+ self._outside_loc = None
+ if isinstance(loc, str):
+ if loc.split()[0] == 'outside':
+ # strip outside:
+ loc = loc.split('outside ')[1]
+ # strip "center" at the beginning
+ self._outside_loc = loc.replace('center ', '')
+ # strip first
+ self._outside_loc = self._outside_loc.split()[0]
+ locs = loc.split()
+ if len(locs) > 1 and locs[0] in ('right', 'left'):
+ # locs doesn't accept "left upper", etc, so swap
+ if locs[0] != 'center':
+ locs = locs[::-1]
+ loc = locs[0] + ' ' + locs[1]
+ # check that loc is in acceptable strings
+ loc = _api.check_getitem(self.codes, loc=loc)
+
+ if self.isaxes and self._outside_loc:
+ raise ValueError(
+ f"'outside' option for loc='{loc0}' keyword argument only "
+ "works for figure legends")
+
+ if not self.isaxes and loc == 0:
+ raise ValueError(
+ "Automatic legend placement (loc='best') not implemented for "
+ "figure legend")
+
+ self._mode = mode
+ self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
+
+ # We use FancyBboxPatch to draw a legend frame. The location
+ # and size of the box will be updated during the drawing time.
+
+ if facecolor is None:
+ facecolor = mpl.rcParams["legend.facecolor"]
+ if facecolor == 'inherit':
+ facecolor = mpl.rcParams["axes.facecolor"]
+
+ if edgecolor is None:
+ edgecolor = mpl.rcParams["legend.edgecolor"]
+ if edgecolor == 'inherit':
+ edgecolor = mpl.rcParams["axes.edgecolor"]
+
+ if fancybox is None:
+ fancybox = mpl.rcParams["legend.fancybox"]
+
+ self.legendPatch = FancyBboxPatch(
+ xy=(0, 0), width=1, height=1,
+ facecolor=facecolor, edgecolor=edgecolor,
+ # If shadow is used, default to alpha=1 (#8943).
+ alpha=(framealpha if framealpha is not None
+ else 1 if shadow
+ else mpl.rcParams["legend.framealpha"]),
+ # The width and height of the legendPatch will be set (in draw())
+ # to the length that includes the padding. Thus we set pad=0 here.
+ boxstyle=("round,pad=0,rounding_size=0.2" if fancybox
+ else "square,pad=0"),
+ mutation_scale=self._fontsize,
+ snap=True,
+ visible=(frameon if frameon is not None
+ else mpl.rcParams["legend.frameon"])
+ )
+ self._set_artist_props(self.legendPatch)
+
+ _api.check_in_list(["center", "left", "right"], alignment=alignment)
+ self._alignment = alignment
+
+ # init with null renderer
+ self._init_legend_box(handles, labels, markerfirst)
+
+ tmp = self._loc_used_default
+ self._set_loc(loc)
+ self._loc_used_default = tmp # ignore changes done by _set_loc
+
+ # figure out title font properties:
+ if title_fontsize is not None and title_fontproperties is not None:
+ raise ValueError(
+ "title_fontsize and title_fontproperties can't be specified "
+ "at the same time. Only use one of them. ")
+ title_prop_fp = FontProperties._from_any(title_fontproperties)
+ if isinstance(title_fontproperties, dict):
+ if "size" not in title_fontproperties:
+ title_fontsize = mpl.rcParams["legend.title_fontsize"]
+ title_prop_fp.set_size(title_fontsize)
+ elif title_fontsize is not None:
+ title_prop_fp.set_size(title_fontsize)
+ elif not isinstance(title_fontproperties, FontProperties):
+ title_fontsize = mpl.rcParams["legend.title_fontsize"]
+ title_prop_fp.set_size(title_fontsize)
+
+ self.set_title(title, prop=title_prop_fp)
+
+ self._draggable = None
+ self.set_draggable(state=draggable)
+
+ # set the text color
+
+ color_getters = { # getter function depends on line or patch
+ 'linecolor': ['get_color', 'get_facecolor'],
+ 'markerfacecolor': ['get_markerfacecolor', 'get_facecolor'],
+ 'mfc': ['get_markerfacecolor', 'get_facecolor'],
+ 'markeredgecolor': ['get_markeredgecolor', 'get_edgecolor'],
+ 'mec': ['get_markeredgecolor', 'get_edgecolor'],
+ }
+ if labelcolor is None:
+ if mpl.rcParams['legend.labelcolor'] is not None:
+ labelcolor = mpl.rcParams['legend.labelcolor']
+ else:
+ labelcolor = mpl.rcParams['text.color']
+ if isinstance(labelcolor, str) and labelcolor in color_getters:
+ getter_names = color_getters[labelcolor]
+ for handle, text in zip(self.legend_handles, self.texts):
+ try:
+ if handle.get_array() is not None:
+ continue
+ except AttributeError:
+ pass
+ for getter_name in getter_names:
+ try:
+ color = getattr(handle, getter_name)()
+ if isinstance(color, np.ndarray):
+ if (
+ color.shape[0] == 1
+ or np.isclose(color, color[0]).all()
+ ):
+ text.set_color(color[0])
+ else:
+ pass
+ else:
+ text.set_color(color)
+ break
+ except AttributeError:
+ pass
+ elif isinstance(labelcolor, str) and labelcolor == 'none':
+ for text in self.texts:
+ text.set_color(labelcolor)
+ elif np.iterable(labelcolor):
+ for text, color in zip(self.texts,
+ itertools.cycle(
+ colors.to_rgba_array(labelcolor))):
+ text.set_color(color)
+ else:
+ raise ValueError(f"Invalid labelcolor: {labelcolor!r}")
+
+ legendHandles = _api.deprecated('3.7', alternative="legend_handles")(
+ property(lambda self: self.legend_handles))
+
+ def _set_artist_props(self, a):
+ """
+ Set the boilerplate props for artists added to axes.
+ """
+ a.set_figure(self.figure)
+ if self.isaxes:
+ # a.set_axes(self.axes)
+ a.axes = self.axes
+
+ a.set_transform(self.get_transform())
+
+ def _set_loc(self, loc):
+ # find_offset function will be provided to _legend_box and
+ # _legend_box will draw itself at the location of the return
+ # value of the find_offset.
+ self._loc_used_default = False
+ self._loc_real = loc
+ self.stale = True
+ self._legend_box.set_offset(self._findoffset)
+
+ def set_ncols(self, ncols):
+ """Set the number of columns."""
+ self._ncols = ncols
+
+ def _get_loc(self):
+ return self._loc_real
+
+ _loc = property(_get_loc, _set_loc)
+
+ def _findoffset(self, width, height, xdescent, ydescent, renderer):
+ """Helper function to locate the legend."""
+
+ if self._loc == 0: # "best".
+ x, y = self._find_best_position(width, height, renderer)
+ elif self._loc in Legend.codes.values(): # Fixed location.
+ bbox = Bbox.from_bounds(0, 0, width, height)
+ x, y = self._get_anchored_bbox(self._loc, bbox,
+ self.get_bbox_to_anchor(),
+ renderer)
+ else: # Axes or figure coordinates.
+ fx, fy = self._loc
+ bbox = self.get_bbox_to_anchor()
+ x, y = bbox.x0 + bbox.width * fx, bbox.y0 + bbox.height * fy
+
+ return x + xdescent, y + ydescent
+
+ @allow_rasterization
+ def draw(self, renderer):
+ # docstring inherited
+ if not self.get_visible():
+ return
+
+ renderer.open_group('legend', gid=self.get_gid())
+
+ fontsize = renderer.points_to_pixels(self._fontsize)
+
+ # if mode == fill, set the width of the legend_box to the
+ # width of the parent (minus pads)
+ if self._mode in ["expand"]:
+ pad = 2 * (self.borderaxespad + self.borderpad) * fontsize
+ self._legend_box.set_width(self.get_bbox_to_anchor().width - pad)
+
+ # update the location and size of the legend. This needs to
+ # be done in any case to clip the figure right.
+ bbox = self._legend_box.get_window_extent(renderer)
+ self.legendPatch.set_bounds(bbox.bounds)
+ self.legendPatch.set_mutation_scale(fontsize)
+
+ if self.shadow:
+ Shadow(self.legendPatch, 2, -2).draw(renderer)
+
+ self.legendPatch.draw(renderer)
+ self._legend_box.draw(renderer)
+
+ renderer.close_group('legend')
+ self.stale = False
+
+ # _default_handler_map defines the default mapping between plot
+ # elements and the legend handlers.
+
+ _default_handler_map = {
+ StemContainer: legend_handler.HandlerStem(),
+ ErrorbarContainer: legend_handler.HandlerErrorbar(),
+ Line2D: legend_handler.HandlerLine2D(),
+ Patch: legend_handler.HandlerPatch(),
+ StepPatch: legend_handler.HandlerStepPatch(),
+ LineCollection: legend_handler.HandlerLineCollection(),
+ RegularPolyCollection: legend_handler.HandlerRegularPolyCollection(),
+ CircleCollection: legend_handler.HandlerCircleCollection(),
+ BarContainer: legend_handler.HandlerPatch(
+ update_func=legend_handler.update_from_first_child),
+ tuple: legend_handler.HandlerTuple(),
+ PathCollection: legend_handler.HandlerPathCollection(),
+ PolyCollection: legend_handler.HandlerPolyCollection()
+ }
+
+ # (get|set|update)_default_handler_maps are public interfaces to
+ # modify the default handler map.
+
+ @classmethod
+ def get_default_handler_map(cls):
+ """Return the global default handler map, shared by all legends."""
+ return cls._default_handler_map
+
+ @classmethod
+ def set_default_handler_map(cls, handler_map):
+ """Set the global default handler map, shared by all legends."""
+ cls._default_handler_map = handler_map
+
+ @classmethod
+ def update_default_handler_map(cls, handler_map):
+ """Update the global default handler map, shared by all legends."""
+ cls._default_handler_map.update(handler_map)
+
+ def get_legend_handler_map(self):
+ """Return this legend instance's handler map."""
+ default_handler_map = self.get_default_handler_map()
+ return ({**default_handler_map, **self._custom_handler_map}
+ if self._custom_handler_map else default_handler_map)
+
+ @staticmethod
+ def get_legend_handler(legend_handler_map, orig_handle):
+ """
+ Return a legend handler from *legend_handler_map* that
+ corresponds to *orig_handler*.
+
+ *legend_handler_map* should be a dictionary object (that is
+ returned by the get_legend_handler_map method).
+
+ It first checks if the *orig_handle* itself is a key in the
+ *legend_handler_map* and return the associated value.
+ Otherwise, it checks for each of the classes in its
+ method-resolution-order. If no matching key is found, it
+ returns ``None``.
+ """
+ try:
+ return legend_handler_map[orig_handle]
+ except (TypeError, KeyError): # TypeError if unhashable.
+ pass
+ for handle_type in type(orig_handle).mro():
+ try:
+ return legend_handler_map[handle_type]
+ except KeyError:
+ pass
+ return None
+
+ def _init_legend_box(self, handles, labels, markerfirst=True):
+ """
+ Initialize the legend_box. The legend_box is an instance of
+ the OffsetBox, which is packed with legend handles and
+ texts. Once packed, their location is calculated during the
+ drawing time.
+ """
+
+ fontsize = self._fontsize
+
+ # legend_box is a HPacker, horizontally packed with columns.
+ # Each column is a VPacker, vertically packed with legend items.
+ # Each legend item is a HPacker packed with:
+ # - handlebox: a DrawingArea which contains the legend handle.
+ # - labelbox: a TextArea which contains the legend text.
+
+ text_list = [] # the list of text instances
+ handle_list = [] # the list of handle instances
+ handles_and_labels = []
+
+ # The approximate height and descent of text. These values are
+ # only used for plotting the legend handle.
+ descent = 0.35 * fontsize * (self.handleheight - 0.7) # heuristic.
+ height = fontsize * self.handleheight - descent
+ # each handle needs to be drawn inside a box of (x, y, w, h) =
+ # (0, -descent, width, height). And their coordinates should
+ # be given in the display coordinates.
+
+ # The transformation of each handle will be automatically set
+ # to self.get_transform(). If the artist does not use its
+ # default transform (e.g., Collections), you need to
+ # manually set their transform to the self.get_transform().
+ legend_handler_map = self.get_legend_handler_map()
+
+ for orig_handle, label in zip(handles, labels):
+ handler = self.get_legend_handler(legend_handler_map, orig_handle)
+ if handler is None:
+ _api.warn_external(
+ "Legend does not support handles for {0} "
+ "instances.\nA proxy artist may be used "
+ "instead.\nSee: https://matplotlib.org/"
+ "stable/tutorials/intermediate/legend_guide.html"
+ "#controlling-the-legend-entries".format(
+ type(orig_handle).__name__))
+ # No handle for this artist, so we just defer to None.
+ handle_list.append(None)
+ else:
+ textbox = TextArea(label, multilinebaseline=True,
+ textprops=dict(
+ verticalalignment='baseline',
+ horizontalalignment='left',
+ fontproperties=self.prop))
+ handlebox = DrawingArea(width=self.handlelength * fontsize,
+ height=height,
+ xdescent=0., ydescent=descent)
+
+ text_list.append(textbox._text)
+ # Create the artist for the legend which represents the
+ # original artist/handle.
+ handle_list.append(handler.legend_artist(self, orig_handle,
+ fontsize, handlebox))
+ handles_and_labels.append((handlebox, textbox))
+
+ columnbox = []
+ # array_split splits n handles_and_labels into ncols columns, with the
+ # first n%ncols columns having an extra entry. filter(len, ...)
+ # handles the case where n < ncols: the last ncols-n columns are empty
+ # and get filtered out.
+ for handles_and_labels_column in filter(
+ len, np.array_split(handles_and_labels, self._ncols)):
+ # pack handlebox and labelbox into itembox
+ itemboxes = [HPacker(pad=0,
+ sep=self.handletextpad * fontsize,
+ children=[h, t] if markerfirst else [t, h],
+ align="baseline")
+ for h, t in handles_and_labels_column]
+ # pack columnbox
+ alignment = "baseline" if markerfirst else "right"
+ columnbox.append(VPacker(pad=0,
+ sep=self.labelspacing * fontsize,
+ align=alignment,
+ children=itemboxes))
+
+ mode = "expand" if self._mode == "expand" else "fixed"
+ sep = self.columnspacing * fontsize
+ self._legend_handle_box = HPacker(pad=0,
+ sep=sep, align="baseline",
+ mode=mode,
+ children=columnbox)
+ self._legend_title_box = TextArea("")
+ self._legend_box = VPacker(pad=self.borderpad * fontsize,
+ sep=self.labelspacing * fontsize,
+ align=self._alignment,
+ children=[self._legend_title_box,
+ self._legend_handle_box])
+ self._legend_box.set_figure(self.figure)
+ self._legend_box.axes = self.axes
+ self.texts = text_list
+ self.legend_handles = handle_list
+
+ def _auto_legend_data(self):
+ """
+ Return display coordinates for hit testing for "best" positioning.
+
+ Returns
+ -------
+ bboxes
+ List of bounding boxes of all patches.
+ lines
+ List of `.Path` corresponding to each line.
+ offsets
+ List of (x, y) offsets of all collection.
+ """
+ assert self.isaxes # always holds, as this is only called internally
+ bboxes = []
+ lines = []
+ offsets = []
+ for artist in self.parent._children:
+ if isinstance(artist, Line2D):
+ lines.append(
+ artist.get_transform().transform_path(artist.get_path()))
+ elif isinstance(artist, Rectangle):
+ bboxes.append(
+ artist.get_bbox().transformed(artist.get_data_transform()))
+ elif isinstance(artist, Patch):
+ lines.append(
+ artist.get_transform().transform_path(artist.get_path()))
+ elif isinstance(artist, Collection):
+ transform, transOffset, hoffsets, _ = artist._prepare_points()
+ if len(hoffsets):
+ for offset in transOffset.transform(hoffsets):
+ offsets.append(offset)
+
+ return bboxes, lines, offsets
+
+ def get_children(self):
+ # docstring inherited
+ return [self._legend_box, self.get_frame()]
+
+ def get_frame(self):
+ """Return the `~.patches.Rectangle` used to frame the legend."""
+ return self.legendPatch
+
+ def get_lines(self):
+ r"""Return the list of `~.lines.Line2D`\s in the legend."""
+ return [h for h in self.legend_handles if isinstance(h, Line2D)]
+
+ def get_patches(self):
+ r"""Return the list of `~.patches.Patch`\s in the legend."""
+ return silent_list('Patch',
+ [h for h in self.legend_handles
+ if isinstance(h, Patch)])
+
+ def get_texts(self):
+ r"""Return the list of `~.text.Text`\s in the legend."""
+ return silent_list('Text', self.texts)
+
+ def set_alignment(self, alignment):
+ """
+ Set the alignment of the legend title and the box of entries.
+
+ The entries are aligned as a single block, so that markers always
+ lined up.
+
+ Parameters
+ ----------
+ alignment : {'center', 'left', 'right'}.
+
+ """
+ _api.check_in_list(["center", "left", "right"], alignment=alignment)
+ self._alignment = alignment
+ self._legend_box.align = alignment
+
+ def get_alignment(self):
+ """Get the alignment value of the legend box"""
+ return self._legend_box.align
+
+ def set_title(self, title, prop=None):
+ """
+ Set legend title and title style.
+
+ Parameters
+ ----------
+ title : str
+ The legend title.
+
+ prop : `.font_manager.FontProperties` or `str` or `pathlib.Path`
+ The font properties of the legend title.
+ If a `str`, it is interpreted as a fontconfig pattern parsed by
+ `.FontProperties`. If a `pathlib.Path`, it is interpreted as the
+ absolute path to a font file.
+
+ """
+ self._legend_title_box._text.set_text(title)
+ if title:
+ self._legend_title_box._text.set_visible(True)
+ self._legend_title_box.set_visible(True)
+ else:
+ self._legend_title_box._text.set_visible(False)
+ self._legend_title_box.set_visible(False)
+
+ if prop is not None:
+ self._legend_title_box._text.set_fontproperties(prop)
+
+ self.stale = True
+
+ def get_title(self):
+ """Return the `.Text` instance for the legend title."""
+ return self._legend_title_box._text
+
+ def get_window_extent(self, renderer=None):
+ # docstring inherited
+ if renderer is None:
+ renderer = self.figure._get_renderer()
+ return self._legend_box.get_window_extent(renderer=renderer)
+
+ def get_tightbbox(self, renderer=None):
+ # docstring inherited
+ return self._legend_box.get_window_extent(renderer)
+
+ def get_frame_on(self):
+ """Get whether the legend box patch is drawn."""
+ return self.legendPatch.get_visible()
+
+ def set_frame_on(self, b):
+ """
+ Set whether the legend box patch is drawn.
+
+ Parameters
+ ----------
+ b : bool
+ """
+ self.legendPatch.set_visible(b)
+ self.stale = True
+
+ draw_frame = set_frame_on # Backcompat alias.
+
+ def get_bbox_to_anchor(self):
+ """Return the bbox that the legend will be anchored to."""
+ if self._bbox_to_anchor is None:
+ return self.parent.bbox
+ else:
+ return self._bbox_to_anchor
+
+ def set_bbox_to_anchor(self, bbox, transform=None):
+ """
+ Set the bbox that the legend will be anchored to.
+
+ Parameters
+ ----------
+ bbox : `~matplotlib.transforms.BboxBase` or tuple
+ The bounding box can be specified in the following ways:
+
+ - A `.BboxBase` instance
+ - A tuple of ``(left, bottom, width, height)`` in the given
+ transform (normalized axes coordinate if None)
+ - A tuple of ``(left, bottom)`` where the width and height will be
+ assumed to be zero.
+ - *None*, to remove the bbox anchoring, and use the parent bbox.
+
+ transform : `~matplotlib.transforms.Transform`, optional
+ A transform to apply to the bounding box. If not specified, this
+ will use a transform to the bounding box of the parent.
+ """
+ if bbox is None:
+ self._bbox_to_anchor = None
+ return
+ elif isinstance(bbox, BboxBase):
+ self._bbox_to_anchor = bbox
+ else:
+ try:
+ l = len(bbox)
+ except TypeError as err:
+ raise ValueError(f"Invalid bbox: {bbox}") from err
+
+ if l == 2:
+ bbox = [bbox[0], bbox[1], 0, 0]
+
+ self._bbox_to_anchor = Bbox.from_bounds(*bbox)
+
+ if transform is None:
+ transform = BboxTransformTo(self.parent.bbox)
+
+ self._bbox_to_anchor = TransformedBbox(self._bbox_to_anchor,
+ transform)
+ self.stale = True
+
+ def _get_anchored_bbox(self, loc, bbox, parentbbox, renderer):
+ """
+ Place the *bbox* inside the *parentbbox* according to a given
+ location code. Return the (x, y) coordinate of the bbox.
+
+ Parameters
+ ----------
+ loc : int
+ A location code in range(1, 11). This corresponds to the possible
+ values for ``self._loc``, excluding "best".
+ bbox : `~matplotlib.transforms.Bbox`
+ bbox to be placed, in display coordinates.
+ parentbbox : `~matplotlib.transforms.Bbox`
+ A parent box which will contain the bbox, in display coordinates.
+ """
+ return offsetbox._get_anchored_bbox(
+ loc, bbox, parentbbox,
+ self.borderaxespad * renderer.points_to_pixels(self._fontsize))
+
+ def _find_best_position(self, width, height, renderer, consider=None):
+ """
+ Determine the best location to place the legend.
+
+ *consider* is a list of ``(x, y)`` pairs to consider as a potential
+ lower-left corner of the legend. All are display coords.
+ """
+ assert self.isaxes # always holds, as this is only called internally
+
+ start_time = time.perf_counter()
+
+ bboxes, lines, offsets = self._auto_legend_data()
+
+ bbox = Bbox.from_bounds(0, 0, width, height)
+ if consider is None:
+ consider = [self._get_anchored_bbox(x, bbox,
+ self.get_bbox_to_anchor(),
+ renderer)
+ for x in range(1, len(self.codes))]
+
+ candidates = []
+ for idx, (l, b) in enumerate(consider):
+ legendBox = Bbox.from_bounds(l, b, width, height)
+ badness = 0
+ # XXX TODO: If markers are present, it would be good to take them
+ # into account when checking vertex overlaps in the next line.
+ badness = (sum(legendBox.count_contains(line.vertices)
+ for line in lines)
+ + legendBox.count_contains(offsets)
+ + legendBox.count_overlaps(bboxes)
+ + sum(line.intersects_bbox(legendBox, filled=False)
+ for line in lines))
+ if badness == 0:
+ return l, b
+ # Include the index to favor lower codes in case of a tie.
+ candidates.append((badness, idx, (l, b)))
+
+ _, _, (l, b) = min(candidates)
+
+ if self._loc_used_default and time.perf_counter() - start_time > 1:
+ _api.warn_external(
+ 'Creating legend with loc="best" can be slow with large '
+ 'amounts of data.')
+
+ return l, b
+
+ def contains(self, event):
+ inside, info = self._default_contains(event)
+ if inside is not None:
+ return inside, info
+ return self.legendPatch.contains(event)
+
+ def set_draggable(self, state, use_blit=False, update='loc'):
+ """
+ Enable or disable mouse dragging support of the legend.
+
+ Parameters
+ ----------
+ state : bool
+ Whether mouse dragging is enabled.
+ use_blit : bool, optional
+ Use blitting for faster image composition. For details see
+ :ref:`func-animation`.
+ update : {'loc', 'bbox'}, optional
+ The legend parameter to be changed when dragged:
+
+ - 'loc': update the *loc* parameter of the legend
+ - 'bbox': update the *bbox_to_anchor* parameter of the legend
+
+ Returns
+ -------
+ `.DraggableLegend` or *None*
+ If *state* is ``True`` this returns the `.DraggableLegend` helper
+ instance. Otherwise this returns *None*.
+ """
+ if state:
+ if self._draggable is None:
+ self._draggable = DraggableLegend(self,
+ use_blit,
+ update=update)
+ else:
+ if self._draggable is not None:
+ self._draggable.disconnect()
+ self._draggable = None
+ return self._draggable
+
+ def get_draggable(self):
+ """Return ``True`` if the legend is draggable, ``False`` otherwise."""
+ return self._draggable is not None
+
+
+# Helper functions to parse legend arguments for both `figure.legend` and
+# `axes.legend`:
+def _get_legend_handles(axs, legend_handler_map=None):
+ """Yield artists that can be used as handles in a legend."""
+ handles_original = []
+ for ax in axs:
+ handles_original += [
+ *(a for a in ax._children
+ if isinstance(a, (Line2D, Patch, Collection, Text))),
+ *ax.containers]
+ # support parasite axes:
+ if hasattr(ax, 'parasites'):
+ for axx in ax.parasites:
+ handles_original += [
+ *(a for a in axx._children
+ if isinstance(a, (Line2D, Patch, Collection, Text))),
+ *axx.containers]
+
+ handler_map = {**Legend.get_default_handler_map(),
+ **(legend_handler_map or {})}
+ has_handler = Legend.get_legend_handler
+ for handle in handles_original:
+ label = handle.get_label()
+ if label != '_nolegend_' and has_handler(handler_map, handle):
+ yield handle
+ elif (label and not label.startswith('_') and
+ not has_handler(handler_map, handle)):
+ _api.warn_external(
+ "Legend does not support handles for {0} "
+ "instances.\nSee: https://matplotlib.org/stable/"
+ "tutorials/intermediate/legend_guide.html"
+ "#implementing-a-custom-legend-handler".format(
+ type(handle).__name__))
+ continue
+
+
+def _get_legend_handles_labels(axs, legend_handler_map=None):
+ """Return handles and labels for legend."""
+ handles = []
+ labels = []
+ for handle in _get_legend_handles(axs, legend_handler_map):
+ label = handle.get_label()
+ if label and not label.startswith('_'):
+ handles.append(handle)
+ labels.append(label)
+ return handles, labels
+
+
+def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
+ """
+ Get the handles and labels from the calls to either ``figure.legend``
+ or ``axes.legend``.
+
+ The parser is a bit involved because we support::
+
+ legend()
+ legend(labels)
+ legend(handles, labels)
+ legend(labels=labels)
+ legend(handles=handles)
+ legend(handles=handles, labels=labels)
+
+ The behavior for a mixture of positional and keyword handles and labels
+ is undefined and issues a warning.
+
+ Parameters
+ ----------
+ axs : list of `.Axes`
+ If handles are not given explicitly, the artists in these Axes are
+ used as handles.
+ *args : tuple
+ Positional parameters passed to ``legend()``.
+ handles
+ The value of the keyword argument ``legend(handles=...)``, or *None*
+ if that keyword argument was not used.
+ labels
+ The value of the keyword argument ``legend(labels=...)``, or *None*
+ if that keyword argument was not used.
+ **kwargs
+ All other keyword arguments passed to ``legend()``.
+
+ Returns
+ -------
+ handles : list of `.Artist`
+ The legend handles.
+ labels : list of str
+ The legend labels.
+ extra_args : tuple
+ *args* with positional handles and labels removed.
+ kwargs : dict
+ *kwargs* with keywords handles and labels removed.
+
+ """
+ log = logging.getLogger(__name__)
+
+ handlers = kwargs.get('handler_map')
+ extra_args = ()
+
+ if (handles is not None or labels is not None) and args:
+ _api.warn_external("You have mixed positional and keyword arguments, "
+ "some input may be discarded.")
+
+ # if got both handles and labels as kwargs, make same length
+ if handles and labels:
+ handles, labels = zip(*zip(handles, labels))
+
+ elif handles is not None and labels is None:
+ labels = [handle.get_label() for handle in handles]
+
+ elif labels is not None and handles is None:
+ # Get as many handles as there are labels.
+ handles = [handle for handle, label
+ in zip(_get_legend_handles(axs, handlers), labels)]
+
+ # No arguments - automatically detect labels and handles.
+ elif len(args) == 0:
+ handles, labels = _get_legend_handles_labels(axs, handlers)
+ if not handles:
+ log.warning(
+ "No artists with labels found to put in legend. Note that "
+ "artists whose label start with an underscore are ignored "
+ "when legend() is called with no argument.")
+
+ # One argument. User defined labels - automatic handle detection.
+ elif len(args) == 1:
+ labels, = args
+ if any(isinstance(l, Artist) for l in labels):
+ raise TypeError("A single argument passed to legend() must be a "
+ "list of labels, but found an Artist in there.")
+
+ # Get as many handles as there are labels.
+ handles = [handle for handle, label
+ in zip(_get_legend_handles(axs, handlers), labels)]
+
+ # Two arguments:
+ # * user defined handles and labels
+ elif len(args) >= 2:
+ handles, labels = args[:2]
+ extra_args = args[2:]
+
+ else:
+ raise TypeError('Invalid arguments to legend.')
+
+ return handles, labels, extra_args, kwargs
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/lines.py b/omnilmm/lib/python3.10/site-packages/matplotlib/lines.py
new file mode 100644
index 0000000000000000000000000000000000000000..129970bc2f4c8149ff1136cfe9b15f90331f11ae
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/lines.py
@@ -0,0 +1,1605 @@
+"""
+2D lines with support for a variety of line styles, markers, colors, etc.
+"""
+
+import copy
+
+from numbers import Integral, Number, Real
+import logging
+
+import numpy as np
+
+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)
+from .markers import MarkerStyle
+from .path import Path
+from .transforms import Bbox, BboxTransformTo, TransformedPath
+from ._enums import JoinStyle, CapStyle
+
+# Imported here for backward compatibility, even though they don't
+# really belong.
+from . import _path
+from .markers import ( # noqa
+ CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN,
+ CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE,
+ TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN)
+
+_log = logging.getLogger(__name__)
+
+
+def _get_dash_pattern(style):
+ """Convert linestyle to dash pattern."""
+ # go from short hand -> full strings
+ if isinstance(style, str):
+ style = ls_mapper.get(style, style)
+ # un-dashed styles
+ if style in ['solid', 'None']:
+ offset = 0
+ dashes = None
+ # dashed styles
+ elif style in ['dashed', 'dashdot', 'dotted']:
+ offset = 0
+ dashes = tuple(mpl.rcParams['lines.{}_pattern'.format(style)])
+ #
+ elif isinstance(style, tuple):
+ offset, dashes = style
+ if offset is None:
+ raise ValueError(f'Unrecognized linestyle: {style!r}')
+ else:
+ raise ValueError(f'Unrecognized linestyle: {style!r}')
+
+ # normalize offset to be positive and shorter than the dash cycle
+ if dashes is not None:
+ dsum = sum(dashes)
+ if dsum:
+ offset %= dsum
+
+ return offset, dashes
+
+
+def _scale_dashes(offset, dashes, lw):
+ 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]
+ if dashes is not None else None)
+ return scaled_offset, scaled_dashes
+
+
+def segment_hits(cx, cy, x, y, radius):
+ """
+ Return the indices of the segments in the polyline with coordinates (*cx*,
+ *cy*) that are within a distance *radius* of the point (*x*, *y*).
+ """
+ # Process single points specially
+ if len(x) <= 1:
+ res, = np.nonzero((cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2)
+ return res
+
+ # We need to lop the last element off a lot.
+ xr, yr = x[:-1], y[:-1]
+
+ # Only look at line segments whose nearest point to C on the line
+ # lies within the segment.
+ dx, dy = x[1:] - xr, y[1:] - yr
+ Lnorm_sq = dx ** 2 + dy ** 2 # Possibly want to eliminate Lnorm==0
+ u = ((cx - xr) * dx + (cy - yr) * dy) / Lnorm_sq
+ candidates = (u >= 0) & (u <= 1)
+
+ # Note that there is a little area near one side of each point
+ # which will be near neither segment, and another which will
+ # be near both, depending on the angle of the lines. The
+ # following radius test eliminates these ambiguities.
+ point_hits = (cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2
+ candidates = candidates & ~(point_hits[:-1] | point_hits[1:])
+
+ # For those candidates which remain, determine how far they lie away
+ # from the line.
+ px, py = xr + u * dx, yr + u * dy
+ line_hits = (cx - px) ** 2 + (cy - py) ** 2 <= radius ** 2
+ line_hits = line_hits & candidates
+ points, = point_hits.ravel().nonzero()
+ lines, = line_hits.ravel().nonzero()
+ return np.concatenate((points, lines))
+
+
+def _mark_every_path(markevery, tpath, affine, ax):
+ """
+ Helper function that sorts out how to deal the input
+ `markevery` and returns the points where markers should be drawn.
+
+ Takes in the `markevery` value and the line path and returns the
+ sub-sampled path.
+ """
+ # pull out the two bits of data we want from the path
+ codes, verts = tpath.codes, tpath.vertices
+
+ def _slice_or_none(in_v, slc):
+ """Helper function to cope with `codes` being an ndarray or `None`."""
+ if in_v is None:
+ return None
+ return in_v[slc]
+
+ # if just an int, assume starting at 0 and make a tuple
+ if isinstance(markevery, Integral):
+ markevery = (0, markevery)
+ # if just a float, assume starting at 0.0 and make a tuple
+ elif isinstance(markevery, Real):
+ markevery = (0.0, markevery)
+
+ if isinstance(markevery, tuple):
+ if len(markevery) != 2:
+ raise ValueError('`markevery` is a tuple but its len is not 2; '
+ 'markevery={}'.format(markevery))
+ start, step = markevery
+ # if step is an int, old behavior
+ if isinstance(step, Integral):
+ # tuple of 2 int is for backwards compatibility,
+ if not isinstance(start, Integral):
+ raise ValueError(
+ '`markevery` is a tuple with len 2 and second element is '
+ 'an int, but the first element is not an int; markevery={}'
+ .format(markevery))
+ # just return, we are done here
+
+ return Path(verts[slice(start, None, step)],
+ _slice_or_none(codes, slice(start, None, step)))
+
+ elif isinstance(step, Real):
+ if not isinstance(start, Real):
+ raise ValueError(
+ '`markevery` is a tuple with len 2 and second element is '
+ 'a float, but the first element is not a float or an int; '
+ 'markevery={}'.format(markevery))
+ if ax is None:
+ raise ValueError(
+ "markevery is specified relative to the axes size, but "
+ "the line does not have a Axes as parent")
+
+ # calc cumulative distance along path (in display coords):
+ fin = np.isfinite(verts).all(axis=1)
+ fverts = verts[fin]
+ disp_coords = affine.transform(fverts)
+
+ delta = np.empty((len(disp_coords), 2))
+ delta[0, :] = 0
+ delta[1:, :] = disp_coords[1:, :] - disp_coords[:-1, :]
+ delta = np.hypot(*delta.T).cumsum()
+ # calc distance between markers along path based on the axes
+ # bounding box diagonal being a distance of unity:
+ (x0, y0), (x1, y1) = ax.transAxes.transform([[0, 0], [1, 1]])
+ scale = np.hypot(x1 - x0, y1 - y0)
+ marker_delta = np.arange(start * scale, delta[-1], step * scale)
+ # find closest actual data point that is closest to
+ # the theoretical distance along the path:
+ inds = np.abs(delta[np.newaxis, :] - marker_delta[:, np.newaxis])
+ inds = inds.argmin(axis=1)
+ inds = np.unique(inds)
+ # return, we are done here
+ return Path(fverts[inds], _slice_or_none(codes, inds))
+ else:
+ raise ValueError(
+ f"markevery={markevery!r} is a tuple with len 2, but its "
+ f"second element is not an int or a float")
+
+ elif isinstance(markevery, slice):
+ # mazol tov, it's already a slice, just return
+ return Path(verts[markevery], _slice_or_none(codes, markevery))
+
+ elif np.iterable(markevery):
+ # fancy indexing
+ try:
+ return Path(verts[markevery], _slice_or_none(codes, markevery))
+ except (ValueError, IndexError) as err:
+ raise ValueError(
+ f"markevery={markevery!r} is iterable but not a valid numpy "
+ f"fancy index") from err
+ else:
+ raise ValueError(f"markevery={markevery!r} is not a recognized value")
+
+
+@_docstring.interpd
+@_api.define_aliases({
+ "antialiased": ["aa"],
+ "color": ["c"],
+ "drawstyle": ["ds"],
+ "linestyle": ["ls"],
+ "linewidth": ["lw"],
+ "markeredgecolor": ["mec"],
+ "markeredgewidth": ["mew"],
+ "markerfacecolor": ["mfc"],
+ "markerfacecoloralt": ["mfcalt"],
+ "markersize": ["ms"],
+})
+class Line2D(Artist):
+ """
+ A line - the line can have both a solid linestyle connecting all
+ the vertices, and a marker at each vertex. Additionally, the
+ drawing of the solid line is influenced by the drawstyle, e.g., one
+ can create "stepped" lines in various styles.
+ """
+
+ lineStyles = _lineStyles = { # hidden names deprecated
+ '-': '_draw_solid',
+ '--': '_draw_dashed',
+ '-.': '_draw_dash_dot',
+ ':': '_draw_dotted',
+ 'None': '_draw_nothing',
+ ' ': '_draw_nothing',
+ '': '_draw_nothing',
+ }
+
+ _drawStyles_l = {
+ 'default': '_draw_lines',
+ 'steps-mid': '_draw_steps_mid',
+ 'steps-pre': '_draw_steps_pre',
+ 'steps-post': '_draw_steps_post',
+ }
+
+ _drawStyles_s = {
+ 'steps': '_draw_steps_pre',
+ }
+
+ # drawStyles should now be deprecated.
+ drawStyles = {**_drawStyles_l, **_drawStyles_s}
+ # Need a list ordered with long names first:
+ drawStyleKeys = [*_drawStyles_l, *_drawStyles_s]
+
+ # Referenced here to maintain API. These are defined in
+ # MarkerStyle
+ markers = MarkerStyle.markers
+ filled_markers = MarkerStyle.filled_markers
+ fillStyles = MarkerStyle.fillstyles
+
+ zorder = 2
+
+ _subslice_optim_min_size = 1000
+
+ def __str__(self):
+ if self._label != "":
+ return f"Line2D({self._label})"
+ elif self._x is None:
+ return "Line2D()"
+ elif len(self._x) > 3:
+ return "Line2D((%g,%g),(%g,%g),...,(%g,%g))" % (
+ self._x[0], self._y[0], self._x[0],
+ self._y[0], self._x[-1], self._y[-1])
+ else:
+ return "Line2D(%s)" % ",".join(
+ map("({:g},{:g})".format, self._x, self._y))
+
+ @_api.make_keyword_only("3.6", name="linewidth")
+ def __init__(self, xdata, ydata,
+ linewidth=None, # all Nones default to rc
+ linestyle=None,
+ color=None,
+ gapcolor=None,
+ marker=None,
+ markersize=None,
+ markeredgewidth=None,
+ markeredgecolor=None,
+ markerfacecolor=None,
+ markerfacecoloralt='none',
+ fillstyle=None,
+ antialiased=None,
+ dash_capstyle=None,
+ solid_capstyle=None,
+ dash_joinstyle=None,
+ solid_joinstyle=None,
+ pickradius=5,
+ drawstyle=None,
+ markevery=None,
+ **kwargs
+ ):
+ """
+ Create a `.Line2D` instance with *x* and *y* data in sequences of
+ *xdata*, *ydata*.
+
+ Additional keyword arguments are `.Line2D` properties:
+
+ %(Line2D:kwdoc)s
+
+ See :meth:`set_linestyle` for a description of the line styles,
+ :meth:`set_marker` for a description of the markers, and
+ :meth:`set_drawstyle` for a description of the draw styles.
+
+ """
+ super().__init__()
+
+ # Convert sequences to NumPy arrays.
+ if not np.iterable(xdata):
+ raise RuntimeError('xdata must be a sequence')
+ if not np.iterable(ydata):
+ raise RuntimeError('ydata must be a sequence')
+
+ if linewidth is None:
+ linewidth = mpl.rcParams['lines.linewidth']
+
+ if linestyle is None:
+ linestyle = mpl.rcParams['lines.linestyle']
+ if marker is None:
+ marker = mpl.rcParams['lines.marker']
+ if color is None:
+ color = mpl.rcParams['lines.color']
+
+ if markersize is None:
+ markersize = mpl.rcParams['lines.markersize']
+ if antialiased is None:
+ antialiased = mpl.rcParams['lines.antialiased']
+ if dash_capstyle is None:
+ dash_capstyle = mpl.rcParams['lines.dash_capstyle']
+ if dash_joinstyle is None:
+ dash_joinstyle = mpl.rcParams['lines.dash_joinstyle']
+ if solid_capstyle is None:
+ solid_capstyle = mpl.rcParams['lines.solid_capstyle']
+ if solid_joinstyle is None:
+ solid_joinstyle = mpl.rcParams['lines.solid_joinstyle']
+
+ if drawstyle is None:
+ drawstyle = 'default'
+
+ self._dashcapstyle = None
+ self._dashjoinstyle = None
+ self._solidjoinstyle = None
+ self._solidcapstyle = None
+ self.set_dash_capstyle(dash_capstyle)
+ self.set_dash_joinstyle(dash_joinstyle)
+ self.set_solid_capstyle(solid_capstyle)
+ self.set_solid_joinstyle(solid_joinstyle)
+
+ self._linestyles = None
+ self._drawstyle = None
+ self._linewidth = linewidth
+ self._unscaled_dash_pattern = (0, None) # offset, dash
+ self._dash_pattern = (0, None) # offset, dash (scaled by linewidth)
+
+ self.set_linewidth(linewidth)
+ self.set_linestyle(linestyle)
+ self.set_drawstyle(drawstyle)
+
+ self._color = None
+ self.set_color(color)
+ if marker is None:
+ marker = 'none' # Default.
+ if not isinstance(marker, MarkerStyle):
+ self._marker = MarkerStyle(marker, fillstyle)
+ else:
+ self._marker = marker
+
+ self._gapcolor = None
+ self.set_gapcolor(gapcolor)
+
+ self._markevery = None
+ self._markersize = None
+ self._antialiased = None
+
+ self.set_markevery(markevery)
+ self.set_antialiased(antialiased)
+ self.set_markersize(markersize)
+
+ self._markeredgecolor = None
+ self._markeredgewidth = None
+ self._markerfacecolor = None
+ self._markerfacecoloralt = None
+
+ self.set_markerfacecolor(markerfacecolor) # Normalizes None to rc.
+ self.set_markerfacecoloralt(markerfacecoloralt)
+ self.set_markeredgecolor(markeredgecolor) # Normalizes None to rc.
+ self.set_markeredgewidth(markeredgewidth)
+
+ # update kwargs before updating data to give the caller a
+ # chance to init axes (and hence unit support)
+ self._internal_update(kwargs)
+ self._pickradius = pickradius
+ self.ind_offset = 0
+ if (isinstance(self._picker, Number) and
+ not isinstance(self._picker, bool)):
+ self._pickradius = self._picker
+
+ self._xorig = np.asarray([])
+ self._yorig = np.asarray([])
+ self._invalidx = True
+ self._invalidy = True
+ self._x = None
+ self._y = None
+ self._xy = None
+ self._path = None
+ self._transformed_path = None
+ self._subslice = False
+ self._x_filled = None # used in subslicing; only x is needed
+
+ self.set_data(xdata, ydata)
+
+ def contains(self, mouseevent):
+ """
+ Test whether *mouseevent* occurred on the line.
+
+ An event is deemed to have occurred "on" the line if it is less
+ than ``self.pickradius`` (default: 5 points) away from it. Use
+ `~.Line2D.get_pickradius` or `~.Line2D.set_pickradius` to get or set
+ the pick radius.
+
+ Parameters
+ ----------
+ mouseevent : `~matplotlib.backend_bases.MouseEvent`
+
+ Returns
+ -------
+ contains : bool
+ Whether any values are within the radius.
+ details : dict
+ A dictionary ``{'ind': pointlist}``, where *pointlist* is a
+ list of points of the line that are within the pickradius around
+ the event position.
+
+ TODO: sort returned indices by distance
+ """
+ inside, info = self._default_contains(mouseevent)
+ if inside is not None:
+ return inside, info
+
+ # Make sure we have data to plot
+ if self._invalidy or self._invalidx:
+ self.recache()
+ if len(self._xy) == 0:
+ return False, {}
+
+ # Convert points to pixels
+ transformed_path = self._get_transformed_path()
+ path, affine = transformed_path.get_transformed_path_and_affine()
+ path = affine.transform_path(path)
+ xy = path.vertices
+ xt = xy[:, 0]
+ yt = xy[:, 1]
+
+ # Convert pick radius from points to pixels
+ if self.figure is None:
+ _log.warning('no figure set when check if mouse is on line')
+ pixels = self._pickradius
+ else:
+ pixels = self.figure.dpi / 72. * self._pickradius
+
+ # The math involved in checking for containment (here and inside of
+ # segment_hits) assumes that it is OK to overflow, so temporarily set
+ # the error flags accordingly.
+ with np.errstate(all='ignore'):
+ # Check for collision
+ if self._linestyle in ['None', None]:
+ # If no line, return the nearby point(s)
+ ind, = np.nonzero(
+ (xt - mouseevent.x) ** 2 + (yt - mouseevent.y) ** 2
+ <= pixels ** 2)
+ else:
+ # If line, return the nearby segment(s)
+ ind = segment_hits(mouseevent.x, mouseevent.y, xt, yt, pixels)
+ if self._drawstyle.startswith("steps"):
+ ind //= 2
+
+ ind += self.ind_offset
+
+ # Return the point(s) within radius
+ return len(ind) > 0, dict(ind=ind)
+
+ def get_pickradius(self):
+ """
+ Return the pick radius used for containment tests.
+
+ See `.contains` for more details.
+ """
+ return self._pickradius
+
+ @_api.rename_parameter("3.6", "d", "pickradius")
+ def set_pickradius(self, pickradius):
+ """
+ Set the pick radius used for containment tests.
+
+ See `.contains` for more details.
+
+ Parameters
+ ----------
+ pickradius : float
+ Pick radius, in points.
+ """
+ if not isinstance(pickradius, Number) or pickradius < 0:
+ raise ValueError("pick radius should be a distance")
+ self._pickradius = pickradius
+
+ pickradius = property(get_pickradius, set_pickradius)
+
+ def get_fillstyle(self):
+ """
+ Return the marker fill style.
+
+ See also `~.Line2D.set_fillstyle`.
+ """
+ return self._marker.get_fillstyle()
+
+ def set_fillstyle(self, fs):
+ """
+ Set the marker fill style.
+
+ Parameters
+ ----------
+ fs : {'full', 'left', 'right', 'bottom', 'top', 'none'}
+ Possible values:
+
+ - 'full': Fill the whole marker with the *markerfacecolor*.
+ - 'left', 'right', 'bottom', 'top': Fill the marker half at
+ the given side with the *markerfacecolor*. The other
+ half of the marker is filled with *markerfacecoloralt*.
+ - 'none': No filling.
+
+ For examples see :ref:`marker_fill_styles`.
+ """
+ self.set_marker(MarkerStyle(self._marker.get_marker(), fs))
+ self.stale = True
+
+ def set_markevery(self, every):
+ """
+ Set the markevery property to subsample the plot when using markers.
+
+ e.g., if ``every=5``, every 5-th marker will be plotted.
+
+ Parameters
+ ----------
+ every : None or int or (int, int) or slice or list[int] or float or \
+(float, float) or list[bool]
+ Which markers to plot.
+
+ - ``every=None``: every point will be plotted.
+ - ``every=N``: every N-th marker will be plotted starting with
+ marker 0.
+ - ``every=(start, N)``: every N-th marker, starting at index
+ *start*, will be plotted.
+ - ``every=slice(start, end, N)``: every N-th marker, starting at
+ index *start*, up to but not including index *end*, will be
+ plotted.
+ - ``every=[i, j, m, ...]``: only markers at the given indices
+ will be plotted.
+ - ``every=[True, False, True, ...]``: only positions that are True
+ will be plotted. The list must have the same length as the data
+ points.
+ - ``every=0.1``, (i.e. a float): markers will be spaced at
+ approximately equal visual distances along the line; the distance
+ along the line between markers is determined by multiplying the
+ display-coordinate distance of the axes bounding-box diagonal
+ by the value of *every*.
+ - ``every=(0.5, 0.1)`` (i.e. a length-2 tuple of float): similar
+ to ``every=0.1`` but the first marker will be offset along the
+ line by 0.5 multiplied by the
+ display-coordinate-diagonal-distance along the line.
+
+ For examples see
+ :doc:`/gallery/lines_bars_and_markers/markevery_demo`.
+
+ Notes
+ -----
+ Setting *markevery* will still only draw markers at actual data points.
+ While the float argument form aims for uniform visual spacing, it has
+ to coerce from the ideal spacing to the nearest available data point.
+ Depending on the number and distribution of data points, the result
+ may still not look evenly spaced.
+
+ When using a start offset to specify the first marker, the offset will
+ be from the first data point which may be different from the first
+ the visible data point if the plot is zoomed in.
+
+ If zooming in on a plot when using float arguments then the actual
+ data points that have markers will change because the distance between
+ markers is always determined from the display-coordinates
+ axes-bounding-box-diagonal regardless of the actual axes data limits.
+
+ """
+ self._markevery = every
+ self.stale = True
+
+ def get_markevery(self):
+ """
+ Return the markevery setting for marker subsampling.
+
+ See also `~.Line2D.set_markevery`.
+ """
+ return self._markevery
+
+ def set_picker(self, p):
+ """
+ Set the event picker details for the line.
+
+ Parameters
+ ----------
+ p : float or callable[[Artist, Event], tuple[bool, dict]]
+ If a float, it is used as the pick radius in points.
+ """
+ if not callable(p):
+ self.set_pickradius(p)
+ self._picker = p
+
+ def get_bbox(self):
+ """Get the bounding box of this line."""
+ bbox = Bbox([[0, 0], [0, 0]])
+ bbox.update_from_data_xy(self.get_xydata())
+ return bbox
+
+ def get_window_extent(self, renderer=None):
+ bbox = Bbox([[0, 0], [0, 0]])
+ trans_data_to_xy = self.get_transform().transform
+ bbox.update_from_data_xy(trans_data_to_xy(self.get_xydata()),
+ ignore=True)
+ # correct for marker size, if any
+ if self._marker:
+ ms = (self._markersize / 72.0 * self.figure.dpi) * 0.5
+ bbox = bbox.padded(ms)
+ return bbox
+
+ def set_data(self, *args):
+ """
+ Set the x and y data.
+
+ Parameters
+ ----------
+ *args : (2, N) array or two 1D arrays
+ """
+ if len(args) == 1:
+ (x, y), = args
+ else:
+ x, y = args
+
+ self.set_xdata(x)
+ self.set_ydata(y)
+
+ def recache_always(self):
+ self.recache(always=True)
+
+ def recache(self, always=False):
+ if always or self._invalidx:
+ xconv = self.convert_xunits(self._xorig)
+ x = _to_unmasked_float_array(xconv).ravel()
+ else:
+ x = self._x
+ if always or self._invalidy:
+ yconv = self.convert_yunits(self._yorig)
+ y = _to_unmasked_float_array(yconv).ravel()
+ else:
+ y = self._y
+
+ self._xy = np.column_stack(np.broadcast_arrays(x, y)).astype(float)
+ self._x, self._y = self._xy.T # views
+
+ self._subslice = False
+ if (self.axes
+ and len(x) > self._subslice_optim_min_size
+ and _path.is_sorted_and_has_non_nan(x)
+ and self.axes.name == 'rectilinear'
+ and self.axes.get_xscale() == 'linear'
+ and self._markevery is None
+ and self.get_clip_on()
+ and self.get_transform() == self.axes.transData):
+ self._subslice = True
+ nanmask = np.isnan(x)
+ if nanmask.any():
+ self._x_filled = self._x.copy()
+ indices = np.arange(len(x))
+ self._x_filled[nanmask] = np.interp(
+ indices[nanmask], indices[~nanmask], self._x[~nanmask])
+ else:
+ self._x_filled = self._x
+
+ if self._path is not None:
+ interpolation_steps = self._path._interpolation_steps
+ else:
+ interpolation_steps = 1
+ xy = STEP_LOOKUP_MAP[self._drawstyle](*self._xy.T)
+ self._path = Path(np.asarray(xy).T,
+ _interpolation_steps=interpolation_steps)
+ self._transformed_path = None
+ self._invalidx = False
+ self._invalidy = False
+
+ def _transform_path(self, subslice=None):
+ """
+ Put a TransformedPath instance at self._transformed_path;
+ all invalidation of the transform is then handled by the
+ TransformedPath instance.
+ """
+ # Masked arrays are now handled by the Path class itself
+ if subslice is not None:
+ xy = STEP_LOOKUP_MAP[self._drawstyle](*self._xy[subslice, :].T)
+ _path = Path(np.asarray(xy).T,
+ _interpolation_steps=self._path._interpolation_steps)
+ else:
+ _path = self._path
+ self._transformed_path = TransformedPath(_path, self.get_transform())
+
+ def _get_transformed_path(self):
+ """Return this line's `~matplotlib.transforms.TransformedPath`."""
+ if self._transformed_path is None:
+ self._transform_path()
+ return self._transformed_path
+
+ def set_transform(self, t):
+ # docstring inherited
+ self._invalidx = True
+ self._invalidy = True
+ super().set_transform(t)
+
+ @allow_rasterization
+ def draw(self, renderer):
+ # docstring inherited
+
+ if not self.get_visible():
+ return
+
+ if self._invalidy or self._invalidx:
+ self.recache()
+ self.ind_offset = 0 # Needed for contains() method.
+ if self._subslice and self.axes:
+ x0, x1 = self.axes.get_xbound()
+ i0 = self._x_filled.searchsorted(x0, 'left')
+ i1 = self._x_filled.searchsorted(x1, 'right')
+ subslice = slice(max(i0 - 1, 0), i1 + 1)
+ self.ind_offset = subslice.start
+ self._transform_path(subslice)
+ else:
+ subslice = None
+
+ if self.get_path_effects():
+ from matplotlib.patheffects import PathEffectRenderer
+ renderer = PathEffectRenderer(self.get_path_effects(), renderer)
+
+ renderer.open_group('line2d', self.get_gid())
+ if self._lineStyles[self._linestyle] != '_draw_nothing':
+ tpath, affine = (self._get_transformed_path()
+ .get_transformed_path_and_affine())
+ if len(tpath.vertices):
+ gc = renderer.new_gc()
+ self._set_gc_clip(gc)
+ gc.set_url(self.get_url())
+
+ gc.set_antialiased(self._antialiased)
+ gc.set_linewidth(self._linewidth)
+
+ if self.is_dashed():
+ cap = self._dashcapstyle
+ join = self._dashjoinstyle
+ else:
+ cap = self._solidcapstyle
+ join = self._solidjoinstyle
+ gc.set_joinstyle(join)
+ gc.set_capstyle(cap)
+ gc.set_snap(self.get_snap())
+ if self.get_sketch_params() is not None:
+ gc.set_sketch_params(*self.get_sketch_params())
+
+ # We first draw a path within the gaps if needed.
+ if self.is_dashed() and self._gapcolor is not None:
+ lc_rgba = mcolors.to_rgba(self._gapcolor, self._alpha)
+ gc.set_foreground(lc_rgba, isRGBA=True)
+
+ # Define the inverse pattern by moving the last gap to the
+ # start of the sequence.
+ dashes = self._dash_pattern[1]
+ gaps = dashes[-1:] + dashes[:-1]
+ # Set the offset so that this new first segment is skipped
+ # (see backend_bases.GraphicsContextBase.set_dashes for
+ # offset definition).
+ offset_gaps = self._dash_pattern[0] + dashes[-1]
+
+ gc.set_dashes(offset_gaps, gaps)
+ renderer.draw_path(gc, tpath, affine.frozen())
+
+ lc_rgba = mcolors.to_rgba(self._color, self._alpha)
+ gc.set_foreground(lc_rgba, isRGBA=True)
+
+ gc.set_dashes(*self._dash_pattern)
+ renderer.draw_path(gc, tpath, affine.frozen())
+ gc.restore()
+
+ if self._marker and self._markersize > 0:
+ gc = renderer.new_gc()
+ self._set_gc_clip(gc)
+ gc.set_url(self.get_url())
+ gc.set_linewidth(self._markeredgewidth)
+ gc.set_antialiased(self._antialiased)
+
+ ec_rgba = mcolors.to_rgba(
+ self.get_markeredgecolor(), self._alpha)
+ fc_rgba = mcolors.to_rgba(
+ self._get_markerfacecolor(), self._alpha)
+ fcalt_rgba = mcolors.to_rgba(
+ self._get_markerfacecolor(alt=True), self._alpha)
+ # If the edgecolor is "auto", it is set according to the *line*
+ # color but inherits the alpha value of the *face* color, if any.
+ if (cbook._str_equal(self._markeredgecolor, "auto")
+ and not cbook._str_lower_equal(
+ self.get_markerfacecolor(), "none")):
+ ec_rgba = ec_rgba[:3] + (fc_rgba[3],)
+ gc.set_foreground(ec_rgba, isRGBA=True)
+ if self.get_sketch_params() is not None:
+ scale, length, randomness = self.get_sketch_params()
+ gc.set_sketch_params(scale/2, length/2, 2*randomness)
+
+ marker = self._marker
+
+ # Markers *must* be drawn ignoring the drawstyle (but don't pay the
+ # recaching if drawstyle is already "default").
+ if self.get_drawstyle() != "default":
+ with cbook._setattr_cm(
+ self, _drawstyle="default", _transformed_path=None):
+ self.recache()
+ self._transform_path(subslice)
+ tpath, affine = (self._get_transformed_path()
+ .get_transformed_points_and_affine())
+ else:
+ tpath, affine = (self._get_transformed_path()
+ .get_transformed_points_and_affine())
+
+ if len(tpath.vertices):
+ # subsample the markers if markevery is not None
+ markevery = self.get_markevery()
+ if markevery is not None:
+ subsampled = _mark_every_path(
+ markevery, tpath, affine, self.axes)
+ else:
+ subsampled = tpath
+
+ snap = marker.get_snap_threshold()
+ if isinstance(snap, Real):
+ snap = renderer.points_to_pixels(self._markersize) >= snap
+ gc.set_snap(snap)
+ gc.set_joinstyle(marker.get_joinstyle())
+ gc.set_capstyle(marker.get_capstyle())
+ marker_path = marker.get_path()
+ marker_trans = marker.get_transform()
+ w = renderer.points_to_pixels(self._markersize)
+
+ if cbook._str_equal(marker.get_marker(), ","):
+ gc.set_linewidth(0)
+ else:
+ # Don't scale for pixels, and don't stroke them
+ marker_trans = marker_trans.scale(w)
+ renderer.draw_markers(gc, marker_path, marker_trans,
+ subsampled, affine.frozen(),
+ fc_rgba)
+
+ alt_marker_path = marker.get_alt_path()
+ if alt_marker_path:
+ alt_marker_trans = marker.get_alt_transform()
+ alt_marker_trans = alt_marker_trans.scale(w)
+ renderer.draw_markers(
+ gc, alt_marker_path, alt_marker_trans, subsampled,
+ affine.frozen(), fcalt_rgba)
+
+ gc.restore()
+
+ renderer.close_group('line2d')
+ self.stale = False
+
+ def get_antialiased(self):
+ """Return whether antialiased rendering is used."""
+ return self._antialiased
+
+ def get_color(self):
+ """
+ Return the line color.
+
+ See also `~.Line2D.set_color`.
+ """
+ return self._color
+
+ def get_drawstyle(self):
+ """
+ Return the drawstyle.
+
+ See also `~.Line2D.set_drawstyle`.
+ """
+ return self._drawstyle
+
+ def get_gapcolor(self):
+ """
+ Return the line gapcolor.
+
+ See also `~.Line2D.set_gapcolor`.
+ """
+ return self._gapcolor
+
+ def get_linestyle(self):
+ """
+ Return the linestyle.
+
+ See also `~.Line2D.set_linestyle`.
+ """
+ return self._linestyle
+
+ def get_linewidth(self):
+ """
+ Return the linewidth in points.
+
+ See also `~.Line2D.set_linewidth`.
+ """
+ return self._linewidth
+
+ def get_marker(self):
+ """
+ Return the line marker.
+
+ See also `~.Line2D.set_marker`.
+ """
+ return self._marker.get_marker()
+
+ def get_markeredgecolor(self):
+ """
+ Return the marker edge color.
+
+ See also `~.Line2D.set_markeredgecolor`.
+ """
+ mec = self._markeredgecolor
+ if cbook._str_equal(mec, 'auto'):
+ if mpl.rcParams['_internal.classic_mode']:
+ if self._marker.get_marker() in ('.', ','):
+ return self._color
+ if (self._marker.is_filled()
+ and self._marker.get_fillstyle() != 'none'):
+ return 'k' # Bad hard-wired default...
+ return self._color
+ else:
+ return mec
+
+ def get_markeredgewidth(self):
+ """
+ Return the marker edge width in points.
+
+ See also `~.Line2D.set_markeredgewidth`.
+ """
+ return self._markeredgewidth
+
+ def _get_markerfacecolor(self, alt=False):
+ if self._marker.get_fillstyle() == 'none':
+ return 'none'
+ fc = self._markerfacecoloralt if alt else self._markerfacecolor
+ if cbook._str_lower_equal(fc, 'auto'):
+ return self._color
+ else:
+ return fc
+
+ def get_markerfacecolor(self):
+ """
+ Return the marker face color.
+
+ See also `~.Line2D.set_markerfacecolor`.
+ """
+ return self._get_markerfacecolor(alt=False)
+
+ def get_markerfacecoloralt(self):
+ """
+ Return the alternate marker face color.
+
+ See also `~.Line2D.set_markerfacecoloralt`.
+ """
+ return self._get_markerfacecolor(alt=True)
+
+ def get_markersize(self):
+ """
+ Return the marker size in points.
+
+ See also `~.Line2D.set_markersize`.
+ """
+ return self._markersize
+
+ def get_data(self, orig=True):
+ """
+ Return the line data as an ``(xdata, ydata)`` pair.
+
+ If *orig* is *True*, return the original data.
+ """
+ return self.get_xdata(orig=orig), self.get_ydata(orig=orig)
+
+ def get_xdata(self, orig=True):
+ """
+ Return the xdata.
+
+ If *orig* is *True*, return the original data, else the
+ processed data.
+ """
+ if orig:
+ return self._xorig
+ if self._invalidx:
+ self.recache()
+ return self._x
+
+ def get_ydata(self, orig=True):
+ """
+ Return the ydata.
+
+ If *orig* is *True*, return the original data, else the
+ processed data.
+ """
+ if orig:
+ return self._yorig
+ if self._invalidy:
+ self.recache()
+ return self._y
+
+ def get_path(self):
+ """Return the `~matplotlib.path.Path` associated with this line."""
+ if self._invalidy or self._invalidx:
+ self.recache()
+ return self._path
+
+ def get_xydata(self):
+ """
+ Return the *xy* data as a Nx2 numpy array.
+ """
+ if self._invalidy or self._invalidx:
+ self.recache()
+ return self._xy
+
+ def set_antialiased(self, b):
+ """
+ Set whether to use antialiased rendering.
+
+ Parameters
+ ----------
+ b : bool
+ """
+ if self._antialiased != b:
+ self.stale = True
+ self._antialiased = b
+
+ def set_color(self, color):
+ """
+ Set the color of the line.
+
+ Parameters
+ ----------
+ color : color
+ """
+ mcolors._check_color_like(color=color)
+ self._color = color
+ self.stale = True
+
+ def set_drawstyle(self, drawstyle):
+ """
+ Set the drawstyle of the plot.
+
+ The drawstyle determines how the points are connected.
+
+ Parameters
+ ----------
+ drawstyle : {'default', 'steps', 'steps-pre', 'steps-mid', \
+'steps-post'}, default: 'default'
+ For 'default', the points are connected with straight lines.
+
+ The steps variants connect the points with step-like lines,
+ i.e. horizontal lines with vertical steps. They differ in the
+ location of the step:
+
+ - 'steps-pre': The step is at the beginning of the line segment,
+ i.e. the line will be at the y-value of point to the right.
+ - 'steps-mid': The step is halfway between the points.
+ - 'steps-post: The step is at the end of the line segment,
+ i.e. the line will be at the y-value of the point to the left.
+ - 'steps' is equal to 'steps-pre' and is maintained for
+ backward-compatibility.
+
+ For examples see :doc:`/gallery/lines_bars_and_markers/step_demo`.
+ """
+ if drawstyle is None:
+ drawstyle = 'default'
+ _api.check_in_list(self.drawStyles, drawstyle=drawstyle)
+ if self._drawstyle != drawstyle:
+ self.stale = True
+ # invalidate to trigger a recache of the path
+ self._invalidx = True
+ self._drawstyle = drawstyle
+
+ def set_gapcolor(self, gapcolor):
+ """
+ Set a color to fill the gaps in the dashed line style.
+
+ .. note::
+
+ Striped lines are created by drawing two interleaved dashed lines.
+ There can be overlaps between those two, which may result in
+ artifacts when using transparency.
+
+ This functionality is experimental and may change.
+
+ Parameters
+ ----------
+ gapcolor : color or None
+ The color with which to fill the gaps. If None, the gaps are
+ unfilled.
+ """
+ if gapcolor is not None:
+ mcolors._check_color_like(color=gapcolor)
+ self._gapcolor = gapcolor
+ self.stale = True
+
+ def set_linewidth(self, w):
+ """
+ Set the line width in points.
+
+ Parameters
+ ----------
+ w : float
+ Line width, in points.
+ """
+ w = float(w)
+ if self._linewidth != w:
+ self.stale = True
+ self._linewidth = w
+ self._dash_pattern = _scale_dashes(*self._unscaled_dash_pattern, w)
+
+ def set_linestyle(self, ls):
+ """
+ Set the linestyle of the line.
+
+ Parameters
+ ----------
+ ls : {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
+ Possible values:
+
+ - A string:
+
+ ========================================== =================
+ linestyle description
+ ========================================== =================
+ ``'-'`` or ``'solid'`` solid line
+ ``'--'`` or ``'dashed'`` dashed line
+ ``'-.'`` or ``'dashdot'`` dash-dotted line
+ ``':'`` or ``'dotted'`` dotted line
+ ``'none'``, ``'None'``, ``' '``, or ``''`` draw nothing
+ ========================================== =================
+
+ - Alternatively a dash tuple of the following form can be
+ provided::
+
+ (offset, onoffseq)
+
+ where ``onoffseq`` is an even length tuple of on and off ink
+ in points. See also :meth:`set_dashes`.
+
+ For examples see :doc:`/gallery/lines_bars_and_markers/linestyles`.
+ """
+ if isinstance(ls, str):
+ if ls in [' ', '', 'none']:
+ ls = 'None'
+ _api.check_in_list([*self._lineStyles, *ls_mapper_r], ls=ls)
+ if ls not in self._lineStyles:
+ ls = ls_mapper_r[ls]
+ self._linestyle = ls
+ else:
+ self._linestyle = '--'
+ self._unscaled_dash_pattern = _get_dash_pattern(ls)
+ self._dash_pattern = _scale_dashes(
+ *self._unscaled_dash_pattern, self._linewidth)
+ self.stale = True
+
+ @_docstring.interpd
+ def set_marker(self, marker):
+ """
+ Set the line marker.
+
+ Parameters
+ ----------
+ marker : marker style string, `~.path.Path` or `~.markers.MarkerStyle`
+ See `~matplotlib.markers` for full description of possible
+ arguments.
+ """
+ self._marker = MarkerStyle(marker, self._marker.get_fillstyle())
+ self.stale = True
+
+ def _set_markercolor(self, name, has_rcdefault, val):
+ if val is None:
+ val = mpl.rcParams[f"lines.{name}"] if has_rcdefault else "auto"
+ attr = f"_{name}"
+ current = getattr(self, attr)
+ if current is None:
+ self.stale = True
+ else:
+ neq = current != val
+ # Much faster than `np.any(current != val)` if no arrays are used.
+ if neq.any() if isinstance(neq, np.ndarray) else neq:
+ self.stale = True
+ setattr(self, attr, val)
+
+ def set_markeredgecolor(self, ec):
+ """
+ Set the marker edge color.
+
+ Parameters
+ ----------
+ ec : color
+ """
+ self._set_markercolor("markeredgecolor", True, ec)
+
+ def set_markerfacecolor(self, fc):
+ """
+ Set the marker face color.
+
+ Parameters
+ ----------
+ fc : color
+ """
+ self._set_markercolor("markerfacecolor", True, fc)
+
+ def set_markerfacecoloralt(self, fc):
+ """
+ Set the alternate marker face color.
+
+ Parameters
+ ----------
+ fc : color
+ """
+ self._set_markercolor("markerfacecoloralt", False, fc)
+
+ def set_markeredgewidth(self, ew):
+ """
+ Set the marker edge width in points.
+
+ Parameters
+ ----------
+ ew : float
+ Marker edge width, in points.
+ """
+ if ew is None:
+ ew = mpl.rcParams['lines.markeredgewidth']
+ if self._markeredgewidth != ew:
+ self.stale = True
+ self._markeredgewidth = ew
+
+ def set_markersize(self, sz):
+ """
+ Set the marker size in points.
+
+ Parameters
+ ----------
+ sz : float
+ Marker size, in points.
+ """
+ sz = float(sz)
+ if self._markersize != sz:
+ self.stale = True
+ self._markersize = sz
+
+ def set_xdata(self, x):
+ """
+ Set the data array for x.
+
+ Parameters
+ ----------
+ x : 1D array
+ """
+ if not np.iterable(x):
+ # When deprecation cycle is completed
+ # raise RuntimeError('x must be a sequence')
+ _api.warn_deprecated(
+ since=3.7,
+ message="Setting data with a non sequence type "
+ "is deprecated since %(since)s and will be "
+ "remove %(removal)s")
+ x = [x, ]
+ self._xorig = copy.copy(x)
+ self._invalidx = True
+ self.stale = True
+
+ def set_ydata(self, y):
+ """
+ Set the data array for y.
+
+ Parameters
+ ----------
+ y : 1D array
+ """
+ if not np.iterable(y):
+ # When deprecation cycle is completed
+ # raise RuntimeError('y must be a sequence')
+ _api.warn_deprecated(
+ since=3.7,
+ message="Setting data with a non sequence type "
+ "is deprecated since %(since)s and will be "
+ "remove %(removal)s")
+ y = [y, ]
+ self._yorig = copy.copy(y)
+ self._invalidy = True
+ self.stale = True
+
+ def set_dashes(self, seq):
+ """
+ Set the dash sequence.
+
+ The dash sequence is a sequence of floats of even length describing
+ the length of dashes and spaces in points.
+
+ For example, (5, 2, 1, 2) describes a sequence of 5 point and 1 point
+ dashes separated by 2 point spaces.
+
+ See also `~.Line2D.set_gapcolor`, which allows those spaces to be
+ filled with a color.
+
+ Parameters
+ ----------
+ seq : sequence of floats (on/off ink in points) or (None, None)
+ If *seq* is empty or ``(None, None)``, the linestyle will be set
+ to solid.
+ """
+ if seq == (None, None) or len(seq) == 0:
+ self.set_linestyle('-')
+ else:
+ self.set_linestyle((0, seq))
+
+ def update_from(self, other):
+ """Copy properties from *other* to self."""
+ super().update_from(other)
+ self._linestyle = other._linestyle
+ self._linewidth = other._linewidth
+ self._color = other._color
+ self._gapcolor = other._gapcolor
+ self._markersize = other._markersize
+ self._markerfacecolor = other._markerfacecolor
+ self._markerfacecoloralt = other._markerfacecoloralt
+ self._markeredgecolor = other._markeredgecolor
+ self._markeredgewidth = other._markeredgewidth
+ self._unscaled_dash_pattern = other._unscaled_dash_pattern
+ self._dash_pattern = other._dash_pattern
+ self._dashcapstyle = other._dashcapstyle
+ self._dashjoinstyle = other._dashjoinstyle
+ self._solidcapstyle = other._solidcapstyle
+ self._solidjoinstyle = other._solidjoinstyle
+
+ self._linestyle = other._linestyle
+ self._marker = MarkerStyle(marker=other._marker)
+ self._drawstyle = other._drawstyle
+
+ @_docstring.interpd
+ def set_dash_joinstyle(self, s):
+ """
+ How to join segments of the line if it `~Line2D.is_dashed`.
+
+ The default joinstyle is :rc:`lines.dash_joinstyle`.
+
+ Parameters
+ ----------
+ s : `.JoinStyle` or %(JoinStyle)s
+ """
+ js = JoinStyle(s)
+ if self._dashjoinstyle != js:
+ self.stale = True
+ self._dashjoinstyle = js
+
+ @_docstring.interpd
+ def set_solid_joinstyle(self, s):
+ """
+ How to join segments if the line is solid (not `~Line2D.is_dashed`).
+
+ The default joinstyle is :rc:`lines.solid_joinstyle`.
+
+ Parameters
+ ----------
+ s : `.JoinStyle` or %(JoinStyle)s
+ """
+ js = JoinStyle(s)
+ if self._solidjoinstyle != js:
+ self.stale = True
+ self._solidjoinstyle = js
+
+ def get_dash_joinstyle(self):
+ """
+ Return the `.JoinStyle` for dashed lines.
+
+ See also `~.Line2D.set_dash_joinstyle`.
+ """
+ return self._dashjoinstyle.name
+
+ def get_solid_joinstyle(self):
+ """
+ Return the `.JoinStyle` for solid lines.
+
+ See also `~.Line2D.set_solid_joinstyle`.
+ """
+ return self._solidjoinstyle.name
+
+ @_docstring.interpd
+ def set_dash_capstyle(self, s):
+ """
+ How to draw the end caps if the line is `~Line2D.is_dashed`.
+
+ The default capstyle is :rc:`lines.dash_capstyle`.
+
+ Parameters
+ ----------
+ s : `.CapStyle` or %(CapStyle)s
+ """
+ cs = CapStyle(s)
+ if self._dashcapstyle != cs:
+ self.stale = True
+ self._dashcapstyle = cs
+
+ @_docstring.interpd
+ def set_solid_capstyle(self, s):
+ """
+ How to draw the end caps if the line is solid (not `~Line2D.is_dashed`)
+
+ The default capstyle is :rc:`lines.solid_capstyle`.
+
+ Parameters
+ ----------
+ s : `.CapStyle` or %(CapStyle)s
+ """
+ cs = CapStyle(s)
+ if self._solidcapstyle != cs:
+ self.stale = True
+ self._solidcapstyle = cs
+
+ def get_dash_capstyle(self):
+ """
+ Return the `.CapStyle` for dashed lines.
+
+ See also `~.Line2D.set_dash_capstyle`.
+ """
+ return self._dashcapstyle.name
+
+ def get_solid_capstyle(self):
+ """
+ Return the `.CapStyle` for solid lines.
+
+ See also `~.Line2D.set_solid_capstyle`.
+ """
+ return self._solidcapstyle.name
+
+ def is_dashed(self):
+ """
+ Return whether line has a dashed linestyle.
+
+ A custom linestyle is assumed to be dashed, we do not inspect the
+ ``onoffseq`` directly.
+
+ See also `~.Line2D.set_linestyle`.
+ """
+ return self._linestyle in ('--', '-.', ':')
+
+
+class _AxLine(Line2D):
+ """
+ A helper class that implements `~.Axes.axline`, by recomputing the artist
+ transform at draw time.
+ """
+
+ def __init__(self, xy1, xy2, slope, **kwargs):
+ super().__init__([0, 1], [0, 1], **kwargs)
+
+ if (xy2 is None and slope is None or
+ xy2 is not None and slope is not None):
+ raise TypeError(
+ "Exactly one of 'xy2' and 'slope' must be given")
+
+ self._slope = slope
+ self._xy1 = xy1
+ self._xy2 = xy2
+
+ def get_transform(self):
+ ax = self.axes
+ points_transform = self._transform - ax.transData + ax.transScale
+
+ if self._xy2 is not None:
+ # two points were given
+ (x1, y1), (x2, y2) = \
+ points_transform.transform([self._xy1, self._xy2])
+ dx = x2 - x1
+ dy = y2 - y1
+ if np.allclose(x1, x2):
+ if np.allclose(y1, y2):
+ raise ValueError(
+ f"Cannot draw a line through two identical points "
+ f"(x={(x1, x2)}, y={(y1, y2)})")
+ slope = np.inf
+ else:
+ slope = dy / dx
+ else:
+ # one point and a slope were given
+ x1, y1 = points_transform.transform(self._xy1)
+ slope = self._slope
+ (vxlo, vylo), (vxhi, vyhi) = ax.transScale.transform(ax.viewLim)
+ # General case: find intersections with view limits in either
+ # direction, and draw between the middle two points.
+ if np.isclose(slope, 0):
+ start = vxlo, y1
+ stop = vxhi, y1
+ elif np.isinf(slope):
+ start = x1, vylo
+ stop = x1, vyhi
+ else:
+ _, start, stop, _ = sorted([
+ (vxlo, y1 + (vxlo - x1) * slope),
+ (vxhi, y1 + (vxhi - x1) * slope),
+ (x1 + (vylo - y1) / slope, vylo),
+ (x1 + (vyhi - y1) / slope, vyhi),
+ ])
+ return (BboxTransformTo(Bbox([start, stop]))
+ + ax.transLimits + ax.transAxes)
+
+ def draw(self, renderer):
+ self._transformed_path = None # Force regen.
+ super().draw(renderer)
+
+
+class VertexSelector:
+ """
+ Manage the callbacks to maintain a list of selected vertices for `.Line2D`.
+ Derived classes should override the `process_selected` method to do
+ something with the picks.
+
+ Here is an example which highlights the selected verts with red circles::
+
+ import numpy as np
+ import matplotlib.pyplot as plt
+ import matplotlib.lines as lines
+
+ class HighlightSelected(lines.VertexSelector):
+ def __init__(self, line, fmt='ro', **kwargs):
+ super().__init__(line)
+ self.markers, = self.axes.plot([], [], fmt, **kwargs)
+
+ def process_selected(self, ind, xs, ys):
+ self.markers.set_data(xs, ys)
+ self.canvas.draw()
+
+ fig, ax = plt.subplots()
+ x, y = np.random.rand(2, 30)
+ line, = ax.plot(x, y, 'bs-', picker=5)
+
+ selector = HighlightSelected(line)
+ plt.show()
+ """
+
+ def __init__(self, line):
+ """
+ Parameters
+ ----------
+ line : `~matplotlib.lines.Line2D`
+ The line must already have been added to an `~.axes.Axes` and must
+ have its picker property set.
+ """
+ if line.axes is None:
+ raise RuntimeError('You must first add the line to the Axes')
+ if line.get_picker() is None:
+ raise RuntimeError('You must first set the picker property '
+ 'of the line')
+ self.axes = line.axes
+ self.line = line
+ self.cid = self.canvas.callbacks._connect_picklable(
+ 'pick_event', self.onpick)
+ self.ind = set()
+
+ canvas = property(lambda self: self.axes.figure.canvas)
+
+ def process_selected(self, ind, xs, ys):
+ """
+ Default "do nothing" implementation of the `process_selected` method.
+
+ Parameters
+ ----------
+ ind : list of int
+ The indices of the selected vertices.
+ xs, ys : array-like
+ The coordinates of the selected vertices.
+ """
+ pass
+
+ def onpick(self, event):
+ """When the line is picked, update the set of selected indices."""
+ if event.artist is not self.line:
+ return
+ self.ind ^= set(event.ind)
+ ind = sorted(self.ind)
+ xdata, ydata = self.line.get_data()
+ self.process_selected(ind, xdata[ind], ydata[ind])
+
+
+lineStyles = Line2D._lineStyles
+lineMarkers = MarkerStyle.markers
+drawStyles = Line2D.drawStyles
+fillStyles = MarkerStyle.fillstyles
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/markers.py b/omnilmm/lib/python3.10/site-packages/matplotlib/markers.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9fc0141939d460fb34265a787edde6c937cdd59
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/markers.py
@@ -0,0 +1,943 @@
+r"""
+Functions to handle markers; used by the marker functionality of
+`~matplotlib.axes.Axes.plot`, `~matplotlib.axes.Axes.scatter`, and
+`~matplotlib.axes.Axes.errorbar`.
+
+All possible markers are defined here:
+
+============================== ====== =========================================
+marker symbol description
+============================== ====== =========================================
+``"."`` |m00| point
+``","`` |m01| pixel
+``"o"`` |m02| circle
+``"v"`` |m03| triangle_down
+``"^"`` |m04| triangle_up
+``"<"`` |m05| triangle_left
+``">"`` |m06| triangle_right
+``"1"`` |m07| tri_down
+``"2"`` |m08| tri_up
+``"3"`` |m09| tri_left
+``"4"`` |m10| tri_right
+``"8"`` |m11| octagon
+``"s"`` |m12| square
+``"p"`` |m13| pentagon
+``"P"`` |m23| plus (filled)
+``"*"`` |m14| star
+``"h"`` |m15| hexagon1
+``"H"`` |m16| hexagon2
+``"+"`` |m17| plus
+``"x"`` |m18| x
+``"X"`` |m24| x (filled)
+``"D"`` |m19| diamond
+``"d"`` |m20| thin_diamond
+``"|"`` |m21| vline
+``"_"`` |m22| hline
+``0`` (``TICKLEFT``) |m25| tickleft
+``1`` (``TICKRIGHT``) |m26| tickright
+``2`` (``TICKUP``) |m27| tickup
+``3`` (``TICKDOWN``) |m28| tickdown
+``4`` (``CARETLEFT``) |m29| caretleft
+``5`` (``CARETRIGHT``) |m30| caretright
+``6`` (``CARETUP``) |m31| caretup
+``7`` (``CARETDOWN``) |m32| caretdown
+``8`` (``CARETLEFTBASE``) |m33| caretleft (centered at base)
+``9`` (``CARETRIGHTBASE``) |m34| caretright (centered at base)
+``10`` (``CARETUPBASE``) |m35| caretup (centered at base)
+``11`` (``CARETDOWNBASE``) |m36| caretdown (centered at base)
+``"none"`` or ``"None"`` nothing
+``" "`` or ``""`` nothing
+``'$...$'`` |m37| Render the string using mathtext.
+ E.g ``"$f$"`` for marker showing the
+ letter ``f``.
+``verts`` A list of (x, y) pairs used for Path
+ vertices. The center of the marker is
+ located at (0, 0) and the size is
+ normalized, such that the created path
+ is encapsulated inside the unit cell.
+path A `~matplotlib.path.Path` instance.
+``(numsides, 0, angle)`` A regular polygon with ``numsides``
+ sides, rotated by ``angle``.
+``(numsides, 1, angle)`` A star-like symbol with ``numsides``
+ sides, rotated by ``angle``.
+``(numsides, 2, angle)`` An asterisk with ``numsides`` sides,
+ rotated by ``angle``.
+============================== ====== =========================================
+
+As a deprecated feature, ``None`` also means 'nothing' when directly
+constructing a `.MarkerStyle`, but note that there are other contexts where
+``marker=None`` instead means "the default marker" (e.g. :rc:`scatter.marker`
+for `.Axes.scatter`).
+
+Note that special symbols can be defined via the
+:doc:`STIX math font `,
+e.g. ``"$\u266B$"``. For an overview over the STIX font symbols refer to the
+`STIX font table `_.
+Also see the :doc:`/gallery/text_labels_and_annotations/stix_fonts_demo`.
+
+Integer numbers from ``0`` to ``11`` create lines and triangles. Those are
+equally accessible via capitalized variables, like ``CARETDOWNBASE``.
+Hence the following are equivalent::
+
+ plt.plot([1, 2, 3], marker=11)
+ plt.plot([1, 2, 3], marker=matplotlib.markers.CARETDOWNBASE)
+
+Markers join and cap styles can be customized by creating a new instance of
+MarkerStyle.
+A MarkerStyle can also have a custom `~matplotlib.transforms.Transform`
+allowing it to be arbitrarily rotated or offset.
+
+Examples showing the use of markers:
+
+* :doc:`/gallery/lines_bars_and_markers/marker_reference`
+* :doc:`/gallery/lines_bars_and_markers/scatter_star_poly`
+* :doc:`/gallery/lines_bars_and_markers/multivariate_marker_plot`
+
+.. |m00| image:: /_static/markers/m00.png
+.. |m01| image:: /_static/markers/m01.png
+.. |m02| image:: /_static/markers/m02.png
+.. |m03| image:: /_static/markers/m03.png
+.. |m04| image:: /_static/markers/m04.png
+.. |m05| image:: /_static/markers/m05.png
+.. |m06| image:: /_static/markers/m06.png
+.. |m07| image:: /_static/markers/m07.png
+.. |m08| image:: /_static/markers/m08.png
+.. |m09| image:: /_static/markers/m09.png
+.. |m10| image:: /_static/markers/m10.png
+.. |m11| image:: /_static/markers/m11.png
+.. |m12| image:: /_static/markers/m12.png
+.. |m13| image:: /_static/markers/m13.png
+.. |m14| image:: /_static/markers/m14.png
+.. |m15| image:: /_static/markers/m15.png
+.. |m16| image:: /_static/markers/m16.png
+.. |m17| image:: /_static/markers/m17.png
+.. |m18| image:: /_static/markers/m18.png
+.. |m19| image:: /_static/markers/m19.png
+.. |m20| image:: /_static/markers/m20.png
+.. |m21| image:: /_static/markers/m21.png
+.. |m22| image:: /_static/markers/m22.png
+.. |m23| image:: /_static/markers/m23.png
+.. |m24| image:: /_static/markers/m24.png
+.. |m25| image:: /_static/markers/m25.png
+.. |m26| image:: /_static/markers/m26.png
+.. |m27| image:: /_static/markers/m27.png
+.. |m28| image:: /_static/markers/m28.png
+.. |m29| image:: /_static/markers/m29.png
+.. |m30| image:: /_static/markers/m30.png
+.. |m31| image:: /_static/markers/m31.png
+.. |m32| image:: /_static/markers/m32.png
+.. |m33| image:: /_static/markers/m33.png
+.. |m34| image:: /_static/markers/m34.png
+.. |m35| image:: /_static/markers/m35.png
+.. |m36| image:: /_static/markers/m36.png
+.. |m37| image:: /_static/markers/m37.png
+"""
+import copy
+
+from collections.abc import Sized
+import inspect
+
+import numpy as np
+
+import matplotlib as mpl
+from . import _api, cbook
+from .path import Path
+from .transforms import IdentityTransform, Affine2D
+from ._enums import JoinStyle, CapStyle
+
+# special-purpose marker identifiers:
+(TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN,
+ CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN,
+ CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE) = range(12)
+
+_empty_path = Path(np.empty((0, 2)))
+
+
+class MarkerStyle:
+ """
+ A class representing marker types.
+
+ Instances are immutable. If you need to change anything, create a new
+ instance.
+
+ Attributes
+ ----------
+ markers : list
+ All known markers.
+ filled_markers : list
+ All known filled markers. This is a subset of *markers*.
+ fillstyles : list
+ The supported fillstyles.
+ """
+
+ markers = {
+ '.': 'point',
+ ',': 'pixel',
+ 'o': 'circle',
+ 'v': 'triangle_down',
+ '^': 'triangle_up',
+ '<': 'triangle_left',
+ '>': 'triangle_right',
+ '1': 'tri_down',
+ '2': 'tri_up',
+ '3': 'tri_left',
+ '4': 'tri_right',
+ '8': 'octagon',
+ 's': 'square',
+ 'p': 'pentagon',
+ '*': 'star',
+ 'h': 'hexagon1',
+ 'H': 'hexagon2',
+ '+': 'plus',
+ 'x': 'x',
+ 'D': 'diamond',
+ 'd': 'thin_diamond',
+ '|': 'vline',
+ '_': 'hline',
+ 'P': 'plus_filled',
+ 'X': 'x_filled',
+ TICKLEFT: 'tickleft',
+ TICKRIGHT: 'tickright',
+ TICKUP: 'tickup',
+ TICKDOWN: 'tickdown',
+ CARETLEFT: 'caretleft',
+ CARETRIGHT: 'caretright',
+ CARETUP: 'caretup',
+ CARETDOWN: 'caretdown',
+ CARETLEFTBASE: 'caretleftbase',
+ CARETRIGHTBASE: 'caretrightbase',
+ CARETUPBASE: 'caretupbase',
+ CARETDOWNBASE: 'caretdownbase',
+ "None": 'nothing',
+ "none": 'nothing',
+ ' ': 'nothing',
+ '': 'nothing'
+ }
+
+ # Just used for informational purposes. is_filled()
+ # is calculated in the _set_* functions.
+ filled_markers = (
+ '.', 'o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd',
+ 'P', 'X')
+
+ fillstyles = ('full', 'left', 'right', 'bottom', 'top', 'none')
+ _half_fillstyles = ('left', 'right', 'bottom', 'top')
+
+ _unset = object() # For deprecation of MarkerStyle().
+
+ def __init__(self, marker=_unset, fillstyle=None,
+ transform=None, capstyle=None, joinstyle=None):
+ """
+ Parameters
+ ----------
+ marker : str, array-like, Path, MarkerStyle, or None
+ - Another instance of *MarkerStyle* copies the details of that
+ ``marker``.
+ - *None* means no marker. This is the deprecated default.
+ - For other possible marker values, see the module docstring
+ `matplotlib.markers`.
+
+ fillstyle : str, default: :rc:`markers.fillstyle`
+ One of 'full', 'left', 'right', 'bottom', 'top', 'none'.
+
+ transform : transforms.Transform, default: None
+ Transform that will be combined with the native transform of the
+ marker.
+
+ capstyle : CapStyle, default: None
+ Cap style that will override the default cap style of the marker.
+
+ joinstyle : JoinStyle, default: None
+ Join style that will override the default join style of the marker.
+ """
+ self._marker_function = None
+ self._user_transform = transform
+ self._user_capstyle = capstyle
+ self._user_joinstyle = joinstyle
+ self._set_fillstyle(fillstyle)
+ # Remove _unset and signature rewriting after deprecation elapses.
+ if marker is self._unset:
+ marker = ""
+ _api.warn_deprecated(
+ "3.6", message="Calling MarkerStyle() with no parameters is "
+ "deprecated since %(since)s; support will be removed "
+ "%(removal)s. Use MarkerStyle('') to construct an empty "
+ "MarkerStyle.")
+ if marker is None:
+ marker = ""
+ _api.warn_deprecated(
+ "3.6", message="MarkerStyle(None) is deprecated since "
+ "%(since)s; support will be removed %(removal)s. Use "
+ "MarkerStyle('') to construct an empty MarkerStyle.")
+ self._set_marker(marker)
+
+ __init__.__signature__ = inspect.signature( # Only for deprecation period.
+ lambda self, marker, fillstyle=None: None)
+
+ def _recache(self):
+ if self._marker_function is None:
+ return
+ self._path = _empty_path
+ self._transform = IdentityTransform()
+ self._alt_path = None
+ self._alt_transform = None
+ self._snap_threshold = None
+ self._joinstyle = JoinStyle.round
+ self._capstyle = self._user_capstyle or CapStyle.butt
+ # Initial guess: Assume the marker is filled unless the fillstyle is
+ # set to 'none'. The marker function will override this for unfilled
+ # markers.
+ self._filled = self._fillstyle != 'none'
+ self._marker_function()
+
+ def __bool__(self):
+ return bool(len(self._path.vertices))
+
+ def is_filled(self):
+ return self._filled
+
+ def get_fillstyle(self):
+ return self._fillstyle
+
+ def _set_fillstyle(self, fillstyle):
+ """
+ Set the fillstyle.
+
+ Parameters
+ ----------
+ fillstyle : {'full', 'left', 'right', 'bottom', 'top', 'none'}
+ The part of the marker surface that is colored with
+ markerfacecolor.
+ """
+ if fillstyle is None:
+ fillstyle = mpl.rcParams['markers.fillstyle']
+ _api.check_in_list(self.fillstyles, fillstyle=fillstyle)
+ self._fillstyle = fillstyle
+ self._recache()
+
+ def get_joinstyle(self):
+ return self._joinstyle.name
+
+ def get_capstyle(self):
+ return self._capstyle.name
+
+ def get_marker(self):
+ return self._marker
+
+ def _set_marker(self, marker):
+ """
+ Set the marker.
+
+ Parameters
+ ----------
+ marker : str, array-like, Path, MarkerStyle, or None, default: None
+ - Another instance of *MarkerStyle* copies the details of that
+ ``marker``.
+ - *None* means no marker.
+ - For other possible marker values see the module docstring
+ `matplotlib.markers`.
+ """
+ if (isinstance(marker, np.ndarray) and marker.ndim == 2 and
+ marker.shape[1] == 2):
+ self._marker_function = self._set_vertices
+ elif isinstance(marker, str) and cbook.is_math_text(marker):
+ self._marker_function = self._set_mathtext_path
+ elif isinstance(marker, Path):
+ self._marker_function = self._set_path_marker
+ elif (isinstance(marker, Sized) and len(marker) in (2, 3) and
+ marker[1] in (0, 1, 2)):
+ self._marker_function = self._set_tuple_marker
+ elif (not isinstance(marker, (np.ndarray, list)) and
+ marker in self.markers):
+ self._marker_function = getattr(
+ self, '_set_' + self.markers[marker])
+ elif isinstance(marker, MarkerStyle):
+ self.__dict__ = copy.deepcopy(marker.__dict__)
+
+ else:
+ try:
+ Path(marker)
+ self._marker_function = self._set_vertices
+ except ValueError as err:
+ raise ValueError('Unrecognized marker style {!r}'
+ .format(marker)) from err
+
+ if not isinstance(marker, MarkerStyle):
+ self._marker = marker
+ self._recache()
+
+ def get_path(self):
+ """
+ Return a `.Path` for the primary part of the marker.
+
+ For unfilled markers this is the whole marker, for filled markers,
+ this is the area to be drawn with *markerfacecolor*.
+ """
+ return self._path
+
+ def get_transform(self):
+ """
+ Return the transform to be applied to the `.Path` from
+ `MarkerStyle.get_path()`.
+ """
+ if self._user_transform is None:
+ return self._transform.frozen()
+ else:
+ return (self._transform + self._user_transform).frozen()
+
+ def get_alt_path(self):
+ """
+ Return a `.Path` for the alternate part of the marker.
+
+ For unfilled markers, this is *None*; for filled markers, this is the
+ area to be drawn with *markerfacecoloralt*.
+ """
+ return self._alt_path
+
+ def get_alt_transform(self):
+ """
+ Return the transform to be applied to the `.Path` from
+ `MarkerStyle.get_alt_path()`.
+ """
+ if self._user_transform is None:
+ return self._alt_transform.frozen()
+ else:
+ return (self._alt_transform + self._user_transform).frozen()
+
+ def get_snap_threshold(self):
+ return self._snap_threshold
+
+ def get_user_transform(self):
+ """Return user supplied part of marker transform."""
+ if self._user_transform is not None:
+ return self._user_transform.frozen()
+
+ def transformed(self, transform: Affine2D):
+ """
+ Return a new version of this marker with the transform applied.
+
+ Parameters
+ ----------
+ transform : Affine2D, default: None
+ Transform will be combined with current user supplied transform.
+ """
+ new_marker = MarkerStyle(self)
+ if new_marker._user_transform is not None:
+ new_marker._user_transform += transform
+ else:
+ new_marker._user_transform = transform
+ return new_marker
+
+ def rotated(self, *, deg=None, rad=None):
+ """
+ Return a new version of this marker rotated by specified angle.
+
+ Parameters
+ ----------
+ deg : float, default: None
+ Rotation angle in degrees.
+
+ rad : float, default: None
+ Rotation angle in radians.
+
+ .. note:: You must specify exactly one of deg or rad.
+ """
+ if deg is None and rad is None:
+ raise ValueError('One of deg or rad is required')
+ if deg is not None and rad is not None:
+ raise ValueError('Only one of deg and rad can be supplied')
+ new_marker = MarkerStyle(self)
+ if new_marker._user_transform is None:
+ new_marker._user_transform = Affine2D()
+
+ if deg is not None:
+ new_marker._user_transform.rotate_deg(deg)
+ if rad is not None:
+ new_marker._user_transform.rotate(rad)
+
+ return new_marker
+
+ def scaled(self, sx, sy=None):
+ """
+ Return new marker scaled by specified scale factors.
+
+ If *sy* is None, the same scale is applied in both the *x*- and
+ *y*-directions.
+
+ Parameters
+ ----------
+ sx : float
+ *X*-direction scaling factor.
+ sy : float, default: None
+ *Y*-direction scaling factor.
+ """
+ if sy is None:
+ sy = sx
+
+ new_marker = MarkerStyle(self)
+ _transform = new_marker._user_transform or Affine2D()
+ new_marker._user_transform = _transform.scale(sx, sy)
+ return new_marker
+
+ def _set_nothing(self):
+ self._filled = False
+
+ def _set_custom_marker(self, path):
+ rescale = np.max(np.abs(path.vertices)) # max of x's and y's.
+ self._transform = Affine2D().scale(0.5 / rescale)
+ self._path = path
+
+ def _set_path_marker(self):
+ self._set_custom_marker(self._marker)
+
+ def _set_vertices(self):
+ self._set_custom_marker(Path(self._marker))
+
+ def _set_tuple_marker(self):
+ marker = self._marker
+ if len(marker) == 2:
+ numsides, rotation = marker[0], 0.0
+ elif len(marker) == 3:
+ numsides, rotation = marker[0], marker[2]
+ symstyle = marker[1]
+ if symstyle == 0:
+ self._path = Path.unit_regular_polygon(numsides)
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+ elif symstyle == 1:
+ self._path = Path.unit_regular_star(numsides)
+ self._joinstyle = self._user_joinstyle or JoinStyle.bevel
+ elif symstyle == 2:
+ self._path = Path.unit_regular_asterisk(numsides)
+ self._filled = False
+ self._joinstyle = self._user_joinstyle or JoinStyle.bevel
+ else:
+ raise ValueError(f"Unexpected tuple marker: {marker}")
+ self._transform = Affine2D().scale(0.5).rotate_deg(rotation)
+
+ def _set_mathtext_path(self):
+ """
+ Draw mathtext markers '$...$' using `.TextPath` object.
+
+ Submitted by tcb
+ """
+ from matplotlib.text import TextPath
+
+ # again, the properties could be initialised just once outside
+ # this function
+ text = TextPath(xy=(0, 0), s=self.get_marker(),
+ usetex=mpl.rcParams['text.usetex'])
+ if len(text.vertices) == 0:
+ return
+
+ xmin, ymin = text.vertices.min(axis=0)
+ xmax, ymax = text.vertices.max(axis=0)
+ width = xmax - xmin
+ height = ymax - ymin
+ max_dim = max(width, height)
+ self._transform = Affine2D() \
+ .translate(-xmin + 0.5 * -width, -ymin + 0.5 * -height) \
+ .scale(1.0 / max_dim)
+ self._path = text
+ self._snap = False
+
+ def _half_fill(self):
+ return self.get_fillstyle() in self._half_fillstyles
+
+ def _set_circle(self, size=1.0):
+ self._transform = Affine2D().scale(0.5 * size)
+ self._snap_threshold = np.inf
+ if not self._half_fill():
+ self._path = Path.unit_circle()
+ else:
+ self._path = self._alt_path = Path.unit_circle_righthalf()
+ fs = self.get_fillstyle()
+ self._transform.rotate_deg(
+ {'right': 0, 'top': 90, 'left': 180, 'bottom': 270}[fs])
+ self._alt_transform = self._transform.frozen().rotate_deg(180.)
+
+ def _set_point(self):
+ self._set_circle(size=0.5)
+
+ def _set_pixel(self):
+ self._path = Path.unit_rectangle()
+ # Ideally, you'd want -0.5, -0.5 here, but then the snapping
+ # algorithm in the Agg backend will round this to a 2x2
+ # rectangle from (-1, -1) to (1, 1). By offsetting it
+ # slightly, we can force it to be (0, 0) to (1, 1), which both
+ # makes it only be a single pixel and places it correctly
+ # aligned to 1-width stroking (i.e. the ticks). This hack is
+ # the best of a number of bad alternatives, mainly because the
+ # backends are not aware of what marker is actually being used
+ # beyond just its path data.
+ self._transform = Affine2D().translate(-0.49999, -0.49999)
+ self._snap_threshold = None
+
+ _triangle_path = Path._create_closed([[0, 1], [-1, -1], [1, -1]])
+ # Going down halfway looks to small. Golden ratio is too far.
+ _triangle_path_u = Path._create_closed([[0, 1], [-3/5, -1/5], [3/5, -1/5]])
+ _triangle_path_d = Path._create_closed(
+ [[-3/5, -1/5], [3/5, -1/5], [1, -1], [-1, -1]])
+ _triangle_path_l = Path._create_closed([[0, 1], [0, -1], [-1, -1]])
+ _triangle_path_r = Path._create_closed([[0, 1], [0, -1], [1, -1]])
+
+ def _set_triangle(self, rot, skip):
+ self._transform = Affine2D().scale(0.5).rotate_deg(rot)
+ self._snap_threshold = 5.0
+
+ if not self._half_fill():
+ self._path = self._triangle_path
+ else:
+ mpaths = [self._triangle_path_u,
+ self._triangle_path_l,
+ self._triangle_path_d,
+ self._triangle_path_r]
+
+ fs = self.get_fillstyle()
+ if fs == 'top':
+ self._path = mpaths[(0 + skip) % 4]
+ self._alt_path = mpaths[(2 + skip) % 4]
+ elif fs == 'bottom':
+ self._path = mpaths[(2 + skip) % 4]
+ self._alt_path = mpaths[(0 + skip) % 4]
+ elif fs == 'left':
+ self._path = mpaths[(1 + skip) % 4]
+ self._alt_path = mpaths[(3 + skip) % 4]
+ else:
+ self._path = mpaths[(3 + skip) % 4]
+ self._alt_path = mpaths[(1 + skip) % 4]
+
+ self._alt_transform = self._transform
+
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+
+ def _set_triangle_up(self):
+ return self._set_triangle(0.0, 0)
+
+ def _set_triangle_down(self):
+ return self._set_triangle(180.0, 2)
+
+ def _set_triangle_left(self):
+ return self._set_triangle(90.0, 3)
+
+ def _set_triangle_right(self):
+ return self._set_triangle(270.0, 1)
+
+ def _set_square(self):
+ self._transform = Affine2D().translate(-0.5, -0.5)
+ self._snap_threshold = 2.0
+ if not self._half_fill():
+ self._path = Path.unit_rectangle()
+ else:
+ # Build a bottom filled square out of two rectangles, one filled.
+ self._path = Path([[0.0, 0.0], [1.0, 0.0], [1.0, 0.5],
+ [0.0, 0.5], [0.0, 0.0]])
+ self._alt_path = Path([[0.0, 0.5], [1.0, 0.5], [1.0, 1.0],
+ [0.0, 1.0], [0.0, 0.5]])
+ fs = self.get_fillstyle()
+ rotate = {'bottom': 0, 'right': 90, 'top': 180, 'left': 270}[fs]
+ self._transform.rotate_deg(rotate)
+ self._alt_transform = self._transform
+
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+
+ def _set_diamond(self):
+ self._transform = Affine2D().translate(-0.5, -0.5).rotate_deg(45)
+ self._snap_threshold = 5.0
+ if not self._half_fill():
+ self._path = Path.unit_rectangle()
+ else:
+ self._path = Path([[0, 0], [1, 0], [1, 1], [0, 0]])
+ self._alt_path = Path([[0, 0], [0, 1], [1, 1], [0, 0]])
+ fs = self.get_fillstyle()
+ rotate = {'right': 0, 'top': 90, 'left': 180, 'bottom': 270}[fs]
+ self._transform.rotate_deg(rotate)
+ self._alt_transform = self._transform
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+
+ def _set_thin_diamond(self):
+ self._set_diamond()
+ self._transform.scale(0.6, 1.0)
+
+ def _set_pentagon(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = 5.0
+
+ polypath = Path.unit_regular_polygon(5)
+
+ if not self._half_fill():
+ self._path = polypath
+ else:
+ verts = polypath.vertices
+ y = (1 + np.sqrt(5)) / 4.
+ top = Path(verts[[0, 1, 4, 0]])
+ bottom = Path(verts[[1, 2, 3, 4, 1]])
+ left = Path([verts[0], verts[1], verts[2], [0, -y], verts[0]])
+ right = Path([verts[0], verts[4], verts[3], [0, -y], verts[0]])
+ self._path, self._alt_path = {
+ 'top': (top, bottom), 'bottom': (bottom, top),
+ 'left': (left, right), 'right': (right, left),
+ }[self.get_fillstyle()]
+ self._alt_transform = self._transform
+
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+
+ def _set_star(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = 5.0
+
+ polypath = Path.unit_regular_star(5, innerCircle=0.381966)
+
+ if not self._half_fill():
+ self._path = polypath
+ else:
+ verts = polypath.vertices
+ top = Path(np.concatenate([verts[0:4], verts[7:10], verts[0:1]]))
+ bottom = Path(np.concatenate([verts[3:8], verts[3:4]]))
+ left = Path(np.concatenate([verts[0:6], verts[0:1]]))
+ right = Path(np.concatenate([verts[0:1], verts[5:10], verts[0:1]]))
+ self._path, self._alt_path = {
+ 'top': (top, bottom), 'bottom': (bottom, top),
+ 'left': (left, right), 'right': (right, left),
+ }[self.get_fillstyle()]
+ self._alt_transform = self._transform
+
+ self._joinstyle = self._user_joinstyle or JoinStyle.bevel
+
+ def _set_hexagon1(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = None
+
+ polypath = Path.unit_regular_polygon(6)
+
+ if not self._half_fill():
+ self._path = polypath
+ else:
+ verts = polypath.vertices
+ # not drawing inside lines
+ x = np.abs(np.cos(5 * np.pi / 6.))
+ top = Path(np.concatenate([[(-x, 0)], verts[[1, 0, 5]], [(x, 0)]]))
+ bottom = Path(np.concatenate([[(-x, 0)], verts[2:5], [(x, 0)]]))
+ left = Path(verts[0:4])
+ right = Path(verts[[0, 5, 4, 3]])
+ self._path, self._alt_path = {
+ 'top': (top, bottom), 'bottom': (bottom, top),
+ 'left': (left, right), 'right': (right, left),
+ }[self.get_fillstyle()]
+ self._alt_transform = self._transform
+
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+
+ def _set_hexagon2(self):
+ self._transform = Affine2D().scale(0.5).rotate_deg(30)
+ self._snap_threshold = None
+
+ polypath = Path.unit_regular_polygon(6)
+
+ if not self._half_fill():
+ self._path = polypath
+ else:
+ verts = polypath.vertices
+ # not drawing inside lines
+ x, y = np.sqrt(3) / 4, 3 / 4.
+ top = Path(verts[[1, 0, 5, 4, 1]])
+ bottom = Path(verts[1:5])
+ left = Path(np.concatenate([
+ [(x, y)], verts[:3], [(-x, -y), (x, y)]]))
+ right = Path(np.concatenate([
+ [(x, y)], verts[5:2:-1], [(-x, -y)]]))
+ self._path, self._alt_path = {
+ 'top': (top, bottom), 'bottom': (bottom, top),
+ 'left': (left, right), 'right': (right, left),
+ }[self.get_fillstyle()]
+ self._alt_transform = self._transform
+
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+
+ def _set_octagon(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = 5.0
+
+ polypath = Path.unit_regular_polygon(8)
+
+ if not self._half_fill():
+ self._transform.rotate_deg(22.5)
+ self._path = polypath
+ else:
+ x = np.sqrt(2.) / 4.
+ self._path = self._alt_path = Path(
+ [[0, -1], [0, 1], [-x, 1], [-1, x],
+ [-1, -x], [-x, -1], [0, -1]])
+ fs = self.get_fillstyle()
+ self._transform.rotate_deg(
+ {'left': 0, 'bottom': 90, 'right': 180, 'top': 270}[fs])
+ self._alt_transform = self._transform.frozen().rotate_deg(180.0)
+
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+
+ _line_marker_path = Path([[0.0, -1.0], [0.0, 1.0]])
+
+ def _set_vline(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = 1.0
+ self._filled = False
+ self._path = self._line_marker_path
+
+ def _set_hline(self):
+ self._set_vline()
+ self._transform = self._transform.rotate_deg(90)
+
+ _tickhoriz_path = Path([[0.0, 0.0], [1.0, 0.0]])
+
+ def _set_tickleft(self):
+ self._transform = Affine2D().scale(-1.0, 1.0)
+ self._snap_threshold = 1.0
+ self._filled = False
+ self._path = self._tickhoriz_path
+
+ def _set_tickright(self):
+ self._transform = Affine2D().scale(1.0, 1.0)
+ self._snap_threshold = 1.0
+ self._filled = False
+ self._path = self._tickhoriz_path
+
+ _tickvert_path = Path([[-0.0, 0.0], [-0.0, 1.0]])
+
+ def _set_tickup(self):
+ self._transform = Affine2D().scale(1.0, 1.0)
+ self._snap_threshold = 1.0
+ self._filled = False
+ self._path = self._tickvert_path
+
+ def _set_tickdown(self):
+ self._transform = Affine2D().scale(1.0, -1.0)
+ self._snap_threshold = 1.0
+ self._filled = False
+ self._path = self._tickvert_path
+
+ _tri_path = Path([[0.0, 0.0], [0.0, -1.0],
+ [0.0, 0.0], [0.8, 0.5],
+ [0.0, 0.0], [-0.8, 0.5]],
+ [Path.MOVETO, Path.LINETO,
+ Path.MOVETO, Path.LINETO,
+ Path.MOVETO, Path.LINETO])
+
+ def _set_tri_down(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = 5.0
+ self._filled = False
+ self._path = self._tri_path
+
+ def _set_tri_up(self):
+ self._set_tri_down()
+ self._transform = self._transform.rotate_deg(180)
+
+ def _set_tri_left(self):
+ self._set_tri_down()
+ self._transform = self._transform.rotate_deg(270)
+
+ def _set_tri_right(self):
+ self._set_tri_down()
+ self._transform = self._transform.rotate_deg(90)
+
+ _caret_path = Path([[-1.0, 1.5], [0.0, 0.0], [1.0, 1.5]])
+
+ def _set_caretdown(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = 3.0
+ self._filled = False
+ self._path = self._caret_path
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+
+ def _set_caretup(self):
+ self._set_caretdown()
+ self._transform = self._transform.rotate_deg(180)
+
+ def _set_caretleft(self):
+ self._set_caretdown()
+ self._transform = self._transform.rotate_deg(270)
+
+ def _set_caretright(self):
+ self._set_caretdown()
+ self._transform = self._transform.rotate_deg(90)
+
+ _caret_path_base = Path([[-1.0, 0.0], [0.0, -1.5], [1.0, 0]])
+
+ def _set_caretdownbase(self):
+ self._set_caretdown()
+ self._path = self._caret_path_base
+
+ def _set_caretupbase(self):
+ self._set_caretdownbase()
+ self._transform = self._transform.rotate_deg(180)
+
+ def _set_caretleftbase(self):
+ self._set_caretdownbase()
+ self._transform = self._transform.rotate_deg(270)
+
+ def _set_caretrightbase(self):
+ self._set_caretdownbase()
+ self._transform = self._transform.rotate_deg(90)
+
+ _plus_path = Path([[-1.0, 0.0], [1.0, 0.0],
+ [0.0, -1.0], [0.0, 1.0]],
+ [Path.MOVETO, Path.LINETO,
+ Path.MOVETO, Path.LINETO])
+
+ def _set_plus(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = 1.0
+ self._filled = False
+ self._path = self._plus_path
+
+ _x_path = Path([[-1.0, -1.0], [1.0, 1.0],
+ [-1.0, 1.0], [1.0, -1.0]],
+ [Path.MOVETO, Path.LINETO,
+ Path.MOVETO, Path.LINETO])
+
+ def _set_x(self):
+ self._transform = Affine2D().scale(0.5)
+ self._snap_threshold = 3.0
+ self._filled = False
+ self._path = self._x_path
+
+ _plus_filled_path = Path._create_closed(np.array([
+ (-1, -3), (+1, -3), (+1, -1), (+3, -1), (+3, +1), (+1, +1),
+ (+1, +3), (-1, +3), (-1, +1), (-3, +1), (-3, -1), (-1, -1)]) / 6)
+ _plus_filled_path_t = Path._create_closed(np.array([
+ (+3, 0), (+3, +1), (+1, +1), (+1, +3),
+ (-1, +3), (-1, +1), (-3, +1), (-3, 0)]) / 6)
+
+ def _set_plus_filled(self):
+ self._transform = Affine2D()
+ self._snap_threshold = 5.0
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+ if not self._half_fill():
+ self._path = self._plus_filled_path
+ else:
+ # Rotate top half path to support all partitions
+ self._path = self._alt_path = self._plus_filled_path_t
+ fs = self.get_fillstyle()
+ self._transform.rotate_deg(
+ {'top': 0, 'left': 90, 'bottom': 180, 'right': 270}[fs])
+ self._alt_transform = self._transform.frozen().rotate_deg(180)
+
+ _x_filled_path = Path._create_closed(np.array([
+ (-1, -2), (0, -1), (+1, -2), (+2, -1), (+1, 0), (+2, +1),
+ (+1, +2), (0, +1), (-1, +2), (-2, +1), (-1, 0), (-2, -1)]) / 4)
+ _x_filled_path_t = Path._create_closed(np.array([
+ (+1, 0), (+2, +1), (+1, +2), (0, +1),
+ (-1, +2), (-2, +1), (-1, 0)]) / 4)
+
+ def _set_x_filled(self):
+ self._transform = Affine2D()
+ self._snap_threshold = 5.0
+ self._joinstyle = self._user_joinstyle or JoinStyle.miter
+ if not self._half_fill():
+ self._path = self._x_filled_path
+ else:
+ # Rotate top half path to support all partitions
+ self._path = self._alt_path = self._x_filled_path_t
+ fs = self.get_fillstyle()
+ self._transform.rotate_deg(
+ {'top': 0, 'left': 90, 'bottom': 180, 'right': 270}[fs])
+ self._alt_transform = self._transform.frozen().rotate_deg(180)
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/mathtext.py b/omnilmm/lib/python3.10/site-packages/matplotlib/mathtext.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc677e83616e479cd6a2d955e00d1c3ea81a0bf6
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/mathtext.py
@@ -0,0 +1,287 @@
+r"""
+A module for parsing a subset of the TeX math syntax and rendering it to a
+Matplotlib backend.
+
+For a tutorial of its usage, see :doc:`/tutorials/text/mathtext`. This
+document is primarily concerned with implementation details.
+
+The module uses pyparsing_ to parse the TeX expression.
+
+.. _pyparsing: https://pypi.org/project/pyparsing/
+
+The Bakoma distribution of the TeX Computer Modern fonts, and STIX
+fonts are supported. There is experimental support for using
+arbitrary fonts, but results may vary without proper tweaking and
+metrics for those fonts.
+"""
+
+from collections import namedtuple
+import functools
+import logging
+
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib import _api, _mathtext
+from matplotlib.ft2font import FT2Image, LOAD_NO_HINTING
+from matplotlib.font_manager import FontProperties
+from ._mathtext import ( # noqa: reexported API
+ RasterParse, VectorParse, get_unicode_index)
+
+_log = logging.getLogger(__name__)
+
+
+get_unicode_index.__module__ = __name__
+
+
+@_api.deprecated("3.6")
+class MathtextBackend:
+ """
+ The base class for the mathtext backend-specific code. `MathtextBackend`
+ subclasses interface between mathtext and specific Matplotlib graphics
+ backends.
+
+ Subclasses need to override the following:
+
+ - :meth:`render_glyph`
+ - :meth:`render_rect_filled`
+ - :meth:`get_results`
+
+ And optionally, if you need to use a FreeType hinting style:
+
+ - :meth:`get_hinting_type`
+ """
+ def __init__(self):
+ self.width = 0
+ self.height = 0
+ self.depth = 0
+
+ def set_canvas_size(self, w, h, d):
+ """Set the dimension of the drawing canvas."""
+ self.width = w
+ self.height = h
+ self.depth = d
+
+ def render_glyph(self, ox, oy, info):
+ """
+ Draw a glyph described by *info* to the reference point (*ox*,
+ *oy*).
+ """
+ raise NotImplementedError()
+
+ def render_rect_filled(self, x1, y1, x2, y2):
+ """
+ Draw a filled black rectangle from (*x1*, *y1*) to (*x2*, *y2*).
+ """
+ raise NotImplementedError()
+
+ def get_results(self, box):
+ """
+ Return a backend-specific tuple to return to the backend after
+ all processing is done.
+ """
+ raise NotImplementedError()
+
+ def get_hinting_type(self):
+ """
+ Get the FreeType hinting type to use with this particular
+ backend.
+ """
+ return LOAD_NO_HINTING
+
+
+@_api.deprecated("3.6")
+class MathtextBackendAgg(MathtextBackend):
+ """
+ Render glyphs and rectangles to an FTImage buffer, which is later
+ transferred to the Agg image by the Agg backend.
+ """
+ def __init__(self):
+ self.ox = 0
+ self.oy = 0
+ self.image = None
+ self.mode = 'bbox'
+ self.bbox = [0, 0, 0, 0]
+ super().__init__()
+
+ def _update_bbox(self, x1, y1, x2, y2):
+ self.bbox = [min(self.bbox[0], x1),
+ min(self.bbox[1], y1),
+ max(self.bbox[2], x2),
+ max(self.bbox[3], y2)]
+
+ def set_canvas_size(self, w, h, d):
+ super().set_canvas_size(w, h, d)
+ if self.mode != 'bbox':
+ self.image = FT2Image(np.ceil(w), np.ceil(h + max(d, 0)))
+
+ def render_glyph(self, ox, oy, info):
+ if self.mode == 'bbox':
+ self._update_bbox(ox + info.metrics.xmin,
+ oy - info.metrics.ymax,
+ ox + info.metrics.xmax,
+ oy - info.metrics.ymin)
+ else:
+ info.font.draw_glyph_to_bitmap(
+ self.image, ox, oy - info.metrics.iceberg, info.glyph,
+ antialiased=mpl.rcParams['text.antialiased'])
+
+ def render_rect_filled(self, x1, y1, x2, y2):
+ if self.mode == 'bbox':
+ self._update_bbox(x1, y1, x2, y2)
+ else:
+ height = max(int(y2 - y1) - 1, 0)
+ if height == 0:
+ center = (y2 + y1) / 2.0
+ y = int(center - (height + 1) / 2.0)
+ else:
+ y = int(y1)
+ self.image.draw_rect_filled(int(x1), y, np.ceil(x2), y + height)
+
+ def get_results(self, box):
+ self.image = None
+ self.mode = 'render'
+ return _mathtext.ship(box).to_raster()
+
+ def get_hinting_type(self):
+ from matplotlib.backends import backend_agg
+ return backend_agg.get_hinting_flag()
+
+
+@_api.deprecated("3.6")
+class MathtextBackendPath(MathtextBackend):
+ """
+ Store information to write a mathtext rendering to the text path
+ machinery.
+ """
+
+ _Result = namedtuple("_Result", "width height depth glyphs rects")
+
+ def __init__(self):
+ super().__init__()
+ self.glyphs = []
+ self.rects = []
+
+ def render_glyph(self, ox, oy, info):
+ oy = self.height - oy + info.offset
+ self.glyphs.append((info.font, info.fontsize, info.num, ox, oy))
+
+ def render_rect_filled(self, x1, y1, x2, y2):
+ self.rects.append((x1, self.height - y2, x2 - x1, y2 - y1))
+
+ def get_results(self, box):
+ return _mathtext.ship(box).to_vector()
+
+
+@_api.deprecated("3.6")
+class MathTextWarning(Warning):
+ pass
+
+
+##############################################################################
+# MAIN
+
+
+class MathTextParser:
+ _parser = None
+ _font_type_mapping = {
+ 'cm': _mathtext.BakomaFonts,
+ 'dejavuserif': _mathtext.DejaVuSerifFonts,
+ 'dejavusans': _mathtext.DejaVuSansFonts,
+ 'stix': _mathtext.StixFonts,
+ 'stixsans': _mathtext.StixSansFonts,
+ 'custom': _mathtext.UnicodeFonts,
+ }
+
+ def __init__(self, output):
+ """
+ Create a MathTextParser for the given backend *output*.
+
+ Parameters
+ ----------
+ output : {"path", "agg"}
+ Whether to return a `VectorParse` ("path") or a
+ `RasterParse` ("agg", or its synonym "macosx").
+ """
+ self._output_type = _api.check_getitem(
+ {"path": "vector", "agg": "raster", "macosx": "raster"},
+ output=output.lower())
+
+ def parse(self, s, dpi=72, prop=None):
+ """
+ Parse the given math expression *s* at the given *dpi*. If *prop* is
+ provided, it is a `.FontProperties` object specifying the "default"
+ font to use in the math expression, used for all non-math text.
+
+ The results are cached, so multiple calls to `parse`
+ with the same expression should be fast.
+
+ Depending on the *output* type, this returns either a `VectorParse` or
+ a `RasterParse`.
+ """
+ # lru_cache can't decorate parse() directly because prop
+ # is mutable; key the cache using an internal copy (see
+ # text._get_text_metrics_with_cache for a similar case).
+ prop = prop.copy() if prop is not None else None
+ return self._parse_cached(s, dpi, prop)
+
+ @functools.lru_cache(50)
+ def _parse_cached(self, s, dpi, prop):
+ from matplotlib.backends import backend_agg
+
+ if prop is None:
+ prop = FontProperties()
+ fontset_class = _api.check_getitem(
+ self._font_type_mapping, fontset=prop.get_math_fontfamily())
+ load_glyph_flags = {
+ "vector": LOAD_NO_HINTING,
+ "raster": backend_agg.get_hinting_flag(),
+ }[self._output_type]
+ fontset = fontset_class(prop, load_glyph_flags)
+
+ fontsize = prop.get_size_in_points()
+
+ if self._parser is None: # Cache the parser globally.
+ self.__class__._parser = _mathtext.Parser()
+
+ box = self._parser.parse(s, fontset, fontsize, dpi)
+ output = _mathtext.ship(box)
+ if self._output_type == "vector":
+ return output.to_vector()
+ elif self._output_type == "raster":
+ return output.to_raster()
+
+
+def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None,
+ *, color=None):
+ """
+ Given a math expression, renders it in a closely-clipped bounding
+ box to an image file.
+
+ Parameters
+ ----------
+ s : str
+ A math expression. The math portion must be enclosed in dollar signs.
+ filename_or_obj : str or path-like or file-like
+ Where to write the image data.
+ prop : `.FontProperties`, optional
+ The size and style of the text.
+ dpi : float, optional
+ The output dpi. If not set, the dpi is determined as for
+ `.Figure.savefig`.
+ format : str, optional
+ The output format, e.g., 'svg', 'pdf', 'ps' or 'png'. If not set, the
+ format is determined as for `.Figure.savefig`.
+ color : str, optional
+ Foreground color, defaults to :rc:`text.color`.
+ """
+ from matplotlib import figure
+
+ parser = MathTextParser('path')
+ width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop)
+
+ fig = figure.Figure(figsize=(width / 72.0, height / 72.0))
+ fig.text(0, depth/height, s, fontproperties=prop, color=color)
+ fig.savefig(filename_or_obj, dpi=dpi, format=format)
+
+ return depth
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/mlab.py b/omnilmm/lib/python3.10/site-packages/matplotlib/mlab.py
new file mode 100644
index 0000000000000000000000000000000000000000..059cf0f1624b6f0bf1144c387210144116d76b16
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/mlab.py
@@ -0,0 +1,987 @@
+"""
+Numerical Python functions written for compatibility with MATLAB
+commands with the same names. Most numerical Python functions can be found in
+the `NumPy`_ and `SciPy`_ libraries. What remains here is code for performing
+spectral computations and kernel density estimations.
+
+.. _NumPy: https://numpy.org
+.. _SciPy: https://www.scipy.org
+
+Spectral functions
+------------------
+
+`cohere`
+ Coherence (normalized cross spectral density)
+
+`csd`
+ Cross spectral density using Welch's average periodogram
+
+`detrend`
+ Remove the mean or best fit line from an array
+
+`psd`
+ Power spectral density using Welch's average periodogram
+
+`specgram`
+ Spectrogram (spectrum over segments of time)
+
+`complex_spectrum`
+ Return the complex-valued frequency spectrum of a signal
+
+`magnitude_spectrum`
+ Return the magnitude of the frequency spectrum of a signal
+
+`angle_spectrum`
+ Return the angle (wrapped phase) of the frequency spectrum of a signal
+
+`phase_spectrum`
+ Return the phase (unwrapped angle) of the frequency spectrum of a signal
+
+`detrend_mean`
+ Remove the mean from a line.
+
+`detrend_linear`
+ Remove the best fit line from a line.
+
+`detrend_none`
+ Return the original line.
+
+`stride_windows`
+ Get all windows in an array in a memory-efficient manner
+"""
+
+import functools
+from numbers import Number
+
+import numpy as np
+
+from matplotlib import _api, _docstring, cbook
+
+
+def window_hanning(x):
+ """
+ Return *x* times the Hanning (or Hann) window of len(*x*).
+
+ See Also
+ --------
+ window_none : Another window algorithm.
+ """
+ return np.hanning(len(x))*x
+
+
+def window_none(x):
+ """
+ No window function; simply return *x*.
+
+ See Also
+ --------
+ window_hanning : Another window algorithm.
+ """
+ return x
+
+
+def detrend(x, key=None, axis=None):
+ """
+ Return *x* with its trend removed.
+
+ Parameters
+ ----------
+ x : array or sequence
+ Array or sequence containing the data.
+
+ key : {'default', 'constant', 'mean', 'linear', 'none'} or function
+ The detrending algorithm to use. 'default', 'mean', and 'constant' are
+ the same as `detrend_mean`. 'linear' is the same as `detrend_linear`.
+ 'none' is the same as `detrend_none`. The default is 'mean'. See the
+ corresponding functions for more details regarding the algorithms. Can
+ also be a function that carries out the detrend operation.
+
+ axis : int
+ The axis along which to do the detrending.
+
+ See Also
+ --------
+ detrend_mean : Implementation of the 'mean' algorithm.
+ detrend_linear : Implementation of the 'linear' algorithm.
+ detrend_none : Implementation of the 'none' algorithm.
+ """
+ if key is None or key in ['constant', 'mean', 'default']:
+ return detrend(x, key=detrend_mean, axis=axis)
+ elif key == 'linear':
+ return detrend(x, key=detrend_linear, axis=axis)
+ elif key == 'none':
+ return detrend(x, key=detrend_none, axis=axis)
+ elif callable(key):
+ x = np.asarray(x)
+ if axis is not None and axis + 1 > x.ndim:
+ raise ValueError(f'axis(={axis}) out of bounds')
+ if (axis is None and x.ndim == 0) or (not axis and x.ndim == 1):
+ return key(x)
+ # try to use the 'axis' argument if the function supports it,
+ # otherwise use apply_along_axis to do it
+ try:
+ return key(x, axis=axis)
+ except TypeError:
+ return np.apply_along_axis(key, axis=axis, arr=x)
+ else:
+ raise ValueError(
+ f"Unknown value for key: {key!r}, must be one of: 'default', "
+ f"'constant', 'mean', 'linear', or a function")
+
+
+def detrend_mean(x, axis=None):
+ """
+ Return *x* minus the mean(*x*).
+
+ Parameters
+ ----------
+ x : array or sequence
+ Array or sequence containing the data
+ Can have any dimensionality
+
+ axis : int
+ The axis along which to take the mean. See `numpy.mean` for a
+ description of this argument.
+
+ See Also
+ --------
+ detrend_linear : Another detrend algorithm.
+ detrend_none : Another detrend algorithm.
+ detrend : A wrapper around all the detrend algorithms.
+ """
+ x = np.asarray(x)
+
+ if axis is not None and axis+1 > x.ndim:
+ raise ValueError('axis(=%s) out of bounds' % axis)
+
+ return x - x.mean(axis, keepdims=True)
+
+
+def detrend_none(x, axis=None):
+ """
+ Return *x*: no detrending.
+
+ Parameters
+ ----------
+ x : any object
+ An object containing the data
+
+ axis : int
+ This parameter is ignored.
+ It is included for compatibility with detrend_mean
+
+ See Also
+ --------
+ detrend_mean : Another detrend algorithm.
+ detrend_linear : Another detrend algorithm.
+ detrend : A wrapper around all the detrend algorithms.
+ """
+ return x
+
+
+def detrend_linear(y):
+ """
+ Return *x* minus best fit line; 'linear' detrending.
+
+ Parameters
+ ----------
+ y : 0-D or 1-D array or sequence
+ Array or sequence containing the data
+
+ See Also
+ --------
+ detrend_mean : Another detrend algorithm.
+ detrend_none : Another detrend algorithm.
+ detrend : A wrapper around all the detrend algorithms.
+ """
+ # This is faster than an algorithm based on linalg.lstsq.
+ y = np.asarray(y)
+
+ if y.ndim > 1:
+ raise ValueError('y cannot have ndim > 1')
+
+ # short-circuit 0-D array.
+ if not y.ndim:
+ return np.array(0., dtype=y.dtype)
+
+ x = np.arange(y.size, dtype=float)
+
+ C = np.cov(x, y, bias=1)
+ b = C[0, 1]/C[0, 0]
+
+ a = y.mean() - b*x.mean()
+ return y - (b*x + a)
+
+
+@_api.deprecated("3.6")
+def stride_windows(x, n, noverlap=None, axis=0):
+ """
+ Get all windows of *x* with length *n* as a single array,
+ using strides to avoid data duplication.
+
+ .. warning::
+
+ It is not safe to write to the output array. Multiple
+ elements may point to the same piece of memory,
+ so modifying one value may change others.
+
+ Parameters
+ ----------
+ x : 1D array or sequence
+ Array or sequence containing the data.
+ n : int
+ The number of data points in each window.
+ noverlap : int, default: 0 (no overlap)
+ The overlap between adjacent windows.
+ axis : int
+ The axis along which the windows will run.
+
+ References
+ ----------
+ `stackoverflow: Rolling window for 1D arrays in Numpy?
+ `_
+ `stackoverflow: Using strides for an efficient moving average filter
+ `_
+ """
+ if noverlap is None:
+ noverlap = 0
+ if np.ndim(x) != 1:
+ raise ValueError('only 1-dimensional arrays can be used')
+ return _stride_windows(x, n, noverlap, axis)
+
+
+def _stride_windows(x, n, noverlap=0, axis=0):
+ # np>=1.20 provides sliding_window_view, and we only ever use axis=0.
+ if hasattr(np.lib.stride_tricks, "sliding_window_view") and axis == 0:
+ if noverlap >= n:
+ raise ValueError('noverlap must be less than n')
+ return np.lib.stride_tricks.sliding_window_view(
+ x, n, axis=0)[::n - noverlap].T
+
+ if noverlap >= n:
+ raise ValueError('noverlap must be less than n')
+ if n < 1:
+ raise ValueError('n cannot be less than 1')
+
+ x = np.asarray(x)
+
+ if n == 1 and noverlap == 0:
+ if axis == 0:
+ return x[np.newaxis]
+ else:
+ return x[np.newaxis].T
+ if n > x.size:
+ raise ValueError('n cannot be greater than the length of x')
+
+ # np.lib.stride_tricks.as_strided easily leads to memory corruption for
+ # non integer shape and strides, i.e. noverlap or n. See #3845.
+ noverlap = int(noverlap)
+ n = int(n)
+
+ step = n - noverlap
+ if axis == 0:
+ shape = (n, (x.shape[-1]-noverlap)//step)
+ strides = (x.strides[0], step*x.strides[0])
+ else:
+ shape = ((x.shape[-1]-noverlap)//step, n)
+ strides = (step*x.strides[0], x.strides[0])
+ return np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides)
+
+
+def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None,
+ window=None, noverlap=None, pad_to=None,
+ sides=None, scale_by_freq=None, mode=None):
+ """
+ Private helper implementing the common parts between the psd, csd,
+ spectrogram and complex, magnitude, angle, and phase spectrums.
+ """
+ if y is None:
+ # if y is None use x for y
+ same_data = True
+ else:
+ # The checks for if y is x are so that we can use the same function to
+ # implement the core of psd(), csd(), and spectrogram() without doing
+ # extra calculations. We return the unaveraged Pxy, freqs, and t.
+ same_data = y is x
+
+ if Fs is None:
+ Fs = 2
+ if noverlap is None:
+ noverlap = 0
+ if detrend_func is None:
+ detrend_func = detrend_none
+ if window is None:
+ window = window_hanning
+
+ # if NFFT is set to None use the whole signal
+ if NFFT is None:
+ NFFT = 256
+
+ if mode is None or mode == 'default':
+ mode = 'psd'
+ _api.check_in_list(
+ ['default', 'psd', 'complex', 'magnitude', 'angle', 'phase'],
+ mode=mode)
+
+ if not same_data and mode != 'psd':
+ raise ValueError("x and y must be equal if mode is not 'psd'")
+
+ # Make sure we're dealing with a numpy array. If y and x were the same
+ # object to start with, keep them that way
+ x = np.asarray(x)
+ if not same_data:
+ y = np.asarray(y)
+
+ if sides is None or sides == 'default':
+ if np.iscomplexobj(x):
+ sides = 'twosided'
+ else:
+ sides = 'onesided'
+ _api.check_in_list(['default', 'onesided', 'twosided'], sides=sides)
+
+ # zero pad x and y up to NFFT if they are shorter than NFFT
+ if len(x) < NFFT:
+ n = len(x)
+ x = np.resize(x, NFFT)
+ x[n:] = 0
+
+ if not same_data and len(y) < NFFT:
+ n = len(y)
+ y = np.resize(y, NFFT)
+ y[n:] = 0
+
+ if pad_to is None:
+ pad_to = NFFT
+
+ if mode != 'psd':
+ scale_by_freq = False
+ elif scale_by_freq is None:
+ scale_by_freq = True
+
+ # For real x, ignore the negative frequencies unless told otherwise
+ if sides == 'twosided':
+ numFreqs = pad_to
+ if pad_to % 2:
+ freqcenter = (pad_to - 1)//2 + 1
+ else:
+ freqcenter = pad_to//2
+ scaling_factor = 1.
+ elif sides == 'onesided':
+ if pad_to % 2:
+ numFreqs = (pad_to + 1)//2
+ else:
+ numFreqs = pad_to//2 + 1
+ scaling_factor = 2.
+
+ if not np.iterable(window):
+ window = window(np.ones(NFFT, x.dtype))
+ if len(window) != NFFT:
+ raise ValueError(
+ "The window length must match the data's first dimension")
+
+ result = _stride_windows(x, NFFT, noverlap)
+ result = detrend(result, detrend_func, axis=0)
+ result = result * window.reshape((-1, 1))
+ result = np.fft.fft(result, n=pad_to, axis=0)[:numFreqs, :]
+ freqs = np.fft.fftfreq(pad_to, 1/Fs)[:numFreqs]
+
+ if not same_data:
+ # if same_data is False, mode must be 'psd'
+ resultY = _stride_windows(y, NFFT, noverlap)
+ resultY = detrend(resultY, detrend_func, axis=0)
+ resultY = resultY * window.reshape((-1, 1))
+ resultY = np.fft.fft(resultY, n=pad_to, axis=0)[:numFreqs, :]
+ result = np.conj(result) * resultY
+ elif mode == 'psd':
+ result = np.conj(result) * result
+ elif mode == 'magnitude':
+ result = np.abs(result) / window.sum()
+ elif mode == 'angle' or mode == 'phase':
+ # we unwrap the phase later to handle the onesided vs. twosided case
+ result = np.angle(result)
+ elif mode == 'complex':
+ result /= window.sum()
+
+ if mode == 'psd':
+
+ # Also include scaling factors for one-sided densities and dividing by
+ # the sampling frequency, if desired. Scale everything, except the DC
+ # component and the NFFT/2 component:
+
+ # if we have a even number of frequencies, don't scale NFFT/2
+ if not NFFT % 2:
+ slc = slice(1, -1, None)
+ # if we have an odd number, just don't scale DC
+ else:
+ slc = slice(1, None, None)
+
+ result[slc] *= scaling_factor
+
+ # MATLAB divides by the sampling frequency so that density function
+ # has units of dB/Hz and can be integrated by the plotted frequency
+ # values. Perform the same scaling here.
+ if scale_by_freq:
+ result /= Fs
+ # Scale the spectrum by the norm of the window to compensate for
+ # windowing loss; see Bendat & Piersol Sec 11.5.2.
+ result /= (window**2).sum()
+ else:
+ # In this case, preserve power in the segment, not amplitude
+ result /= window.sum()**2
+
+ t = np.arange(NFFT/2, len(x) - NFFT/2 + 1, NFFT - noverlap)/Fs
+
+ if sides == 'twosided':
+ # center the frequency range at zero
+ freqs = np.roll(freqs, -freqcenter, axis=0)
+ result = np.roll(result, -freqcenter, axis=0)
+ elif not pad_to % 2:
+ # get the last value correctly, it is negative otherwise
+ freqs[-1] *= -1
+
+ # we unwrap the phase here to handle the onesided vs. twosided case
+ if mode == 'phase':
+ result = np.unwrap(result, axis=0)
+
+ return result, freqs, t
+
+
+def _single_spectrum_helper(
+ mode, x, Fs=None, window=None, pad_to=None, sides=None):
+ """
+ Private helper implementing the commonality between the complex, magnitude,
+ angle, and phase spectrums.
+ """
+ _api.check_in_list(['complex', 'magnitude', 'angle', 'phase'], mode=mode)
+
+ if pad_to is None:
+ pad_to = len(x)
+
+ spec, freqs, _ = _spectral_helper(x=x, y=None, NFFT=len(x), Fs=Fs,
+ detrend_func=detrend_none, window=window,
+ noverlap=0, pad_to=pad_to,
+ sides=sides,
+ scale_by_freq=False,
+ mode=mode)
+ if mode != 'complex':
+ spec = spec.real
+
+ if spec.ndim == 2 and spec.shape[1] == 1:
+ spec = spec[:, 0]
+
+ return spec, freqs
+
+
+# Split out these keyword docs so that they can be used elsewhere
+_docstring.interpd.update(
+ Spectral="""\
+Fs : float, default: 2
+ The sampling frequency (samples per time unit). It is used to calculate
+ the Fourier frequencies, *freqs*, in cycles per time unit.
+
+window : callable or ndarray, default: `.window_hanning`
+ A function or a vector of length *NFFT*. To create window vectors see
+ `.window_hanning`, `.window_none`, `numpy.blackman`, `numpy.hamming`,
+ `numpy.bartlett`, `scipy.signal`, `scipy.signal.get_window`, etc. If a
+ function is passed as the argument, it must take a data segment as an
+ argument and return the windowed version of the segment.
+
+sides : {'default', 'onesided', 'twosided'}, optional
+ Which sides of the spectrum to return. 'default' is one-sided for real
+ data and two-sided for complex data. 'onesided' forces the return of a
+ one-sided spectrum, while 'twosided' forces two-sided.""",
+
+ Single_Spectrum="""\
+pad_to : int, optional
+ The number of points to which the data segment is padded when performing
+ the FFT. While not increasing the actual resolution of the spectrum (the
+ minimum distance between resolvable peaks), this can give more points in
+ the plot, allowing for more detail. This corresponds to the *n* parameter
+ in the call to `~numpy.fft.fft`. The default is None, which sets *pad_to*
+ equal to the length of the input signal (i.e. no padding).""",
+
+ PSD="""\
+pad_to : int, optional
+ The number of points to which the data segment is padded when performing
+ the FFT. This can be different from *NFFT*, which specifies the number
+ of data points used. While not increasing the actual resolution of the
+ spectrum (the minimum distance between resolvable peaks), this can give
+ more points in the plot, allowing for more detail. This corresponds to
+ the *n* parameter in the call to `~numpy.fft.fft`. The default is None,
+ which sets *pad_to* equal to *NFFT*
+
+NFFT : int, default: 256
+ The number of data points used in each block for the FFT. A power 2 is
+ most efficient. This should *NOT* be used to get zero padding, or the
+ scaling of the result will be incorrect; use *pad_to* for this instead.
+
+detrend : {'none', 'mean', 'linear'} or callable, default: 'none'
+ The function applied to each segment before fft-ing, designed to remove
+ the mean or linear trend. Unlike in MATLAB, where the *detrend* parameter
+ is a vector, in Matplotlib it is a function. The :mod:`~matplotlib.mlab`
+ module defines `.detrend_none`, `.detrend_mean`, and `.detrend_linear`,
+ but you can use a custom function as well. You can also use a string to
+ choose one of the functions: 'none' calls `.detrend_none`. 'mean' calls
+ `.detrend_mean`. 'linear' calls `.detrend_linear`.
+
+scale_by_freq : bool, default: True
+ Whether the resulting density values should be scaled by the scaling
+ frequency, which gives density in units of 1/Hz. This allows for
+ integration over the returned frequency values. The default is True for
+ MATLAB compatibility.""")
+
+
+@_docstring.dedent_interpd
+def psd(x, NFFT=None, Fs=None, detrend=None, window=None,
+ noverlap=None, pad_to=None, sides=None, scale_by_freq=None):
+ r"""
+ Compute the power spectral density.
+
+ The power spectral density :math:`P_{xx}` by Welch's average
+ periodogram method. The vector *x* is divided into *NFFT* length
+ segments. Each segment is detrended by function *detrend* and
+ windowed by function *window*. *noverlap* gives the length of
+ the overlap between segments. The :math:`|\mathrm{fft}(i)|^2`
+ of each segment :math:`i` are averaged to compute :math:`P_{xx}`.
+
+ If len(*x*) < *NFFT*, it will be zero padded to *NFFT*.
+
+ Parameters
+ ----------
+ x : 1-D array or sequence
+ Array or sequence containing the data
+
+ %(Spectral)s
+
+ %(PSD)s
+
+ noverlap : int, default: 0 (no overlap)
+ The number of points of overlap between segments.
+
+ Returns
+ -------
+ Pxx : 1-D array
+ The values for the power spectrum :math:`P_{xx}` (real valued)
+
+ freqs : 1-D array
+ The frequencies corresponding to the elements in *Pxx*
+
+ References
+ ----------
+ Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John
+ Wiley & Sons (1986)
+
+ See Also
+ --------
+ specgram
+ `specgram` differs in the default overlap; in not returning the mean of
+ the segment periodograms; and in returning the times of the segments.
+
+ magnitude_spectrum : returns the magnitude spectrum.
+
+ csd : returns the spectral density between two signals.
+ """
+ Pxx, freqs = csd(x=x, y=None, NFFT=NFFT, Fs=Fs, detrend=detrend,
+ window=window, noverlap=noverlap, pad_to=pad_to,
+ sides=sides, scale_by_freq=scale_by_freq)
+ return Pxx.real, freqs
+
+
+@_docstring.dedent_interpd
+def csd(x, y, NFFT=None, Fs=None, detrend=None, window=None,
+ noverlap=None, pad_to=None, sides=None, scale_by_freq=None):
+ """
+ Compute the cross-spectral density.
+
+ The cross spectral density :math:`P_{xy}` by Welch's average
+ periodogram method. The vectors *x* and *y* are divided into
+ *NFFT* length segments. Each segment is detrended by function
+ *detrend* and windowed by function *window*. *noverlap* gives
+ the length of the overlap between segments. The product of
+ the direct FFTs of *x* and *y* are averaged over each segment
+ to compute :math:`P_{xy}`, with a scaling to correct for power
+ loss due to windowing.
+
+ If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero
+ padded to *NFFT*.
+
+ Parameters
+ ----------
+ x, y : 1-D arrays or sequences
+ Arrays or sequences containing the data
+
+ %(Spectral)s
+
+ %(PSD)s
+
+ noverlap : int, default: 0 (no overlap)
+ The number of points of overlap between segments.
+
+ Returns
+ -------
+ Pxy : 1-D array
+ The values for the cross spectrum :math:`P_{xy}` before scaling (real
+ valued)
+
+ freqs : 1-D array
+ The frequencies corresponding to the elements in *Pxy*
+
+ References
+ ----------
+ Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John
+ Wiley & Sons (1986)
+
+ See Also
+ --------
+ psd : equivalent to setting ``y = x``.
+ """
+ if NFFT is None:
+ NFFT = 256
+ Pxy, freqs, _ = _spectral_helper(x=x, y=y, NFFT=NFFT, Fs=Fs,
+ detrend_func=detrend, window=window,
+ noverlap=noverlap, pad_to=pad_to,
+ sides=sides, scale_by_freq=scale_by_freq,
+ mode='psd')
+
+ if Pxy.ndim == 2:
+ if Pxy.shape[1] > 1:
+ Pxy = Pxy.mean(axis=1)
+ else:
+ Pxy = Pxy[:, 0]
+ return Pxy, freqs
+
+
+_single_spectrum_docs = """\
+Compute the {quantity} of *x*.
+Data is padded to a length of *pad_to* and the windowing function *window* is
+applied to the signal.
+
+Parameters
+----------
+x : 1-D array or sequence
+ Array or sequence containing the data
+
+{Spectral}
+
+{Single_Spectrum}
+
+Returns
+-------
+spectrum : 1-D array
+ The {quantity}.
+freqs : 1-D array
+ The frequencies corresponding to the elements in *spectrum*.
+
+See Also
+--------
+psd
+ Returns the power spectral density.
+complex_spectrum
+ Returns the complex-valued frequency spectrum.
+magnitude_spectrum
+ Returns the absolute value of the `complex_spectrum`.
+angle_spectrum
+ Returns the angle of the `complex_spectrum`.
+phase_spectrum
+ Returns the phase (unwrapped angle) of the `complex_spectrum`.
+specgram
+ Can return the complex spectrum of segments within the signal.
+"""
+
+
+complex_spectrum = functools.partial(_single_spectrum_helper, "complex")
+complex_spectrum.__doc__ = _single_spectrum_docs.format(
+ quantity="complex-valued frequency spectrum",
+ **_docstring.interpd.params)
+magnitude_spectrum = functools.partial(_single_spectrum_helper, "magnitude")
+magnitude_spectrum.__doc__ = _single_spectrum_docs.format(
+ quantity="magnitude (absolute value) of the frequency spectrum",
+ **_docstring.interpd.params)
+angle_spectrum = functools.partial(_single_spectrum_helper, "angle")
+angle_spectrum.__doc__ = _single_spectrum_docs.format(
+ quantity="angle of the frequency spectrum (wrapped phase spectrum)",
+ **_docstring.interpd.params)
+phase_spectrum = functools.partial(_single_spectrum_helper, "phase")
+phase_spectrum.__doc__ = _single_spectrum_docs.format(
+ quantity="phase of the frequency spectrum (unwrapped phase spectrum)",
+ **_docstring.interpd.params)
+
+
+@_docstring.dedent_interpd
+def specgram(x, NFFT=None, Fs=None, detrend=None, window=None,
+ noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
+ mode=None):
+ """
+ Compute a spectrogram.
+
+ Compute and plot a spectrogram of data in *x*. Data are split into
+ *NFFT* length segments and the spectrum of each section is
+ computed. The windowing function *window* is applied to each
+ segment, and the amount of overlap of each segment is
+ specified with *noverlap*.
+
+ Parameters
+ ----------
+ x : array-like
+ 1-D array or sequence.
+
+ %(Spectral)s
+
+ %(PSD)s
+
+ noverlap : int, default: 128
+ The number of points of overlap between blocks.
+ mode : str, default: 'psd'
+ What sort of spectrum to use:
+ 'psd'
+ Returns the power spectral density.
+ 'complex'
+ Returns the complex-valued frequency spectrum.
+ 'magnitude'
+ Returns the magnitude spectrum.
+ 'angle'
+ Returns the phase spectrum without unwrapping.
+ 'phase'
+ Returns the phase spectrum with unwrapping.
+
+ Returns
+ -------
+ spectrum : array-like
+ 2D array, columns are the periodograms of successive segments.
+
+ freqs : array-like
+ 1-D array, frequencies corresponding to the rows in *spectrum*.
+
+ t : array-like
+ 1-D array, the times corresponding to midpoints of segments
+ (i.e the columns in *spectrum*).
+
+ See Also
+ --------
+ psd : differs in the overlap and in the return values.
+ complex_spectrum : similar, but with complex valued frequencies.
+ magnitude_spectrum : similar single segment when *mode* is 'magnitude'.
+ angle_spectrum : similar to single segment when *mode* is 'angle'.
+ phase_spectrum : similar to single segment when *mode* is 'phase'.
+
+ Notes
+ -----
+ *detrend* and *scale_by_freq* only apply when *mode* is set to 'psd'.
+
+ """
+ if noverlap is None:
+ noverlap = 128 # default in _spectral_helper() is noverlap = 0
+ if NFFT is None:
+ NFFT = 256 # same default as in _spectral_helper()
+ if len(x) <= NFFT:
+ _api.warn_external("Only one segment is calculated since parameter "
+ f"NFFT (={NFFT}) >= signal length (={len(x)}).")
+
+ spec, freqs, t = _spectral_helper(x=x, y=None, NFFT=NFFT, Fs=Fs,
+ detrend_func=detrend, window=window,
+ noverlap=noverlap, pad_to=pad_to,
+ sides=sides,
+ scale_by_freq=scale_by_freq,
+ mode=mode)
+
+ if mode != 'complex':
+ spec = spec.real # Needed since helper implements generically
+
+ return spec, freqs, t
+
+
+@_docstring.dedent_interpd
+def cohere(x, y, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning,
+ noverlap=0, pad_to=None, sides='default', scale_by_freq=None):
+ r"""
+ The coherence between *x* and *y*. Coherence is the normalized
+ cross spectral density:
+
+ .. math::
+
+ C_{xy} = \frac{|P_{xy}|^2}{P_{xx}P_{yy}}
+
+ Parameters
+ ----------
+ x, y
+ Array or sequence containing the data
+
+ %(Spectral)s
+
+ %(PSD)s
+
+ noverlap : int, default: 0 (no overlap)
+ The number of points of overlap between segments.
+
+ Returns
+ -------
+ Cxy : 1-D array
+ The coherence vector.
+ freqs : 1-D array
+ The frequencies for the elements in *Cxy*.
+
+ See Also
+ --------
+ :func:`psd`, :func:`csd` :
+ For information about the methods used to compute :math:`P_{xy}`,
+ :math:`P_{xx}` and :math:`P_{yy}`.
+ """
+ if len(x) < 2 * NFFT:
+ raise ValueError(
+ "Coherence is calculated by averaging over *NFFT* length "
+ "segments. Your signal is too short for your choice of *NFFT*.")
+ Pxx, f = psd(x, NFFT, Fs, detrend, window, noverlap, pad_to, sides,
+ scale_by_freq)
+ Pyy, f = psd(y, NFFT, Fs, detrend, window, noverlap, pad_to, sides,
+ scale_by_freq)
+ Pxy, f = csd(x, y, NFFT, Fs, detrend, window, noverlap, pad_to, sides,
+ scale_by_freq)
+ Cxy = np.abs(Pxy) ** 2 / (Pxx * Pyy)
+ return Cxy, f
+
+
+class GaussianKDE:
+ """
+ Representation of a kernel-density estimate using Gaussian kernels.
+
+ Parameters
+ ----------
+ dataset : array-like
+ Datapoints to estimate from. In case of univariate data this is a 1-D
+ array, otherwise a 2D array with shape (# of dims, # of data).
+ bw_method : str, scalar or callable, optional
+ The method used to calculate the estimator bandwidth. This can be
+ 'scott', 'silverman', a scalar constant or a callable. If a
+ scalar, this will be used directly as `kde.factor`. If a
+ callable, it should take a `GaussianKDE` instance as only
+ parameter and return a scalar. If None (default), 'scott' is used.
+
+ Attributes
+ ----------
+ dataset : ndarray
+ The dataset passed to the constructor.
+ dim : int
+ Number of dimensions.
+ num_dp : int
+ Number of datapoints.
+ factor : float
+ The bandwidth factor, obtained from `kde.covariance_factor`, with which
+ the covariance matrix is multiplied.
+ covariance : ndarray
+ The covariance matrix of *dataset*, scaled by the calculated bandwidth
+ (`kde.factor`).
+ inv_cov : ndarray
+ The inverse of *covariance*.
+
+ Methods
+ -------
+ kde.evaluate(points) : ndarray
+ Evaluate the estimated pdf on a provided set of points.
+ kde(points) : ndarray
+ Same as kde.evaluate(points)
+ """
+
+ # This implementation with minor modification was too good to pass up.
+ # from scipy: https://github.com/scipy/scipy/blob/master/scipy/stats/kde.py
+
+ def __init__(self, dataset, bw_method=None):
+ self.dataset = np.atleast_2d(dataset)
+ if not np.array(self.dataset).size > 1:
+ raise ValueError("`dataset` input should have multiple elements.")
+
+ self.dim, self.num_dp = np.array(self.dataset).shape
+
+ if bw_method is None:
+ pass
+ elif cbook._str_equal(bw_method, 'scott'):
+ self.covariance_factor = self.scotts_factor
+ elif cbook._str_equal(bw_method, 'silverman'):
+ self.covariance_factor = self.silverman_factor
+ elif isinstance(bw_method, Number):
+ self._bw_method = 'use constant'
+ self.covariance_factor = lambda: bw_method
+ elif callable(bw_method):
+ self._bw_method = bw_method
+ self.covariance_factor = lambda: self._bw_method(self)
+ else:
+ raise ValueError("`bw_method` should be 'scott', 'silverman', a "
+ "scalar or a callable")
+
+ # Computes the covariance matrix for each Gaussian kernel using
+ # covariance_factor().
+
+ self.factor = self.covariance_factor()
+ # Cache covariance and inverse covariance of the data
+ if not hasattr(self, '_data_inv_cov'):
+ self.data_covariance = np.atleast_2d(
+ np.cov(
+ self.dataset,
+ rowvar=1,
+ bias=False))
+ self.data_inv_cov = np.linalg.inv(self.data_covariance)
+
+ self.covariance = self.data_covariance * self.factor ** 2
+ self.inv_cov = self.data_inv_cov / self.factor ** 2
+ self.norm_factor = (np.sqrt(np.linalg.det(2 * np.pi * self.covariance))
+ * self.num_dp)
+
+ def scotts_factor(self):
+ return np.power(self.num_dp, -1. / (self.dim + 4))
+
+ def silverman_factor(self):
+ return np.power(
+ self.num_dp * (self.dim + 2.0) / 4.0, -1. / (self.dim + 4))
+
+ # Default method to calculate bandwidth, can be overwritten by subclass
+ covariance_factor = scotts_factor
+
+ def evaluate(self, points):
+ """
+ Evaluate the estimated pdf on a set of points.
+
+ Parameters
+ ----------
+ points : (# of dimensions, # of points)-array
+ Alternatively, a (# of dimensions,) vector can be passed in and
+ treated as a single point.
+
+ Returns
+ -------
+ (# of points,)-array
+ The values at each point.
+
+ Raises
+ ------
+ ValueError : if the dimensionality of the input points is different
+ than the dimensionality of the KDE.
+
+ """
+ points = np.atleast_2d(points)
+
+ dim, num_m = np.array(points).shape
+ if dim != self.dim:
+ raise ValueError("points have dimension {}, dataset has dimension "
+ "{}".format(dim, self.dim))
+
+ result = np.zeros(num_m)
+
+ if num_m >= self.num_dp:
+ # there are more points than data, so loop over data
+ for i in range(self.num_dp):
+ diff = self.dataset[:, i, np.newaxis] - points
+ tdiff = np.dot(self.inv_cov, diff)
+ energy = np.sum(diff * tdiff, axis=0) / 2.0
+ result = result + np.exp(-energy)
+ else:
+ # loop over points
+ for i in range(num_m):
+ diff = self.dataset - points[:, i, np.newaxis]
+ tdiff = np.dot(self.inv_cov, diff)
+ energy = np.sum(diff * tdiff, axis=0) / 2.0
+ result[i] = np.sum(np.exp(-energy), axis=0)
+
+ result = result / self.norm_factor
+
+ return result
+
+ __call__ = evaluate
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/offsetbox.py b/omnilmm/lib/python3.10/site-packages/matplotlib/offsetbox.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd4ddef00eb8fb39f8d8a36ef818a7f75cc2a350
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/offsetbox.py
@@ -0,0 +1,1624 @@
+r"""
+Container classes for `.Artist`\s.
+
+`OffsetBox`
+ The base of all container artists defined in this module.
+
+`AnchoredOffsetbox`, `AnchoredText`
+ Anchor and align an arbitrary `.Artist` or a text relative to the parent
+ axes or a specific anchor point.
+
+`DrawingArea`
+ A container with fixed width and height. Children have a fixed position
+ inside the container and may be clipped.
+
+`HPacker`, `VPacker`
+ Containers for layouting their children vertically or horizontally.
+
+`PaddedBox`
+ A container to add a padding around an `.Artist`.
+
+`TextArea`
+ Contains a single `.Text` instance.
+"""
+
+import functools
+
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib import _api, _docstring
+import matplotlib.artist as martist
+import matplotlib.path as mpath
+import matplotlib.text as mtext
+import matplotlib.transforms as mtransforms
+from matplotlib.font_manager import FontProperties
+from matplotlib.image import BboxImage
+from matplotlib.patches import (
+ FancyBboxPatch, FancyArrowPatch, bbox_artist as mbbox_artist)
+from matplotlib.transforms import Bbox, BboxBase, TransformedBbox
+
+
+DEBUG = False
+
+
+def _compat_get_offset(meth):
+ """
+ Decorator for the get_offset method of OffsetBox and subclasses, that
+ allows supporting both the new signature (self, bbox, renderer) and the old
+ signature (self, width, height, xdescent, ydescent, renderer).
+ """
+ sigs = [lambda self, width, height, xdescent, ydescent, renderer: locals(),
+ lambda self, bbox, renderer: locals()]
+
+ @functools.wraps(meth)
+ def get_offset(self, *args, **kwargs):
+ params = _api.select_matching_signature(sigs, self, *args, **kwargs)
+ bbox = (params["bbox"] if "bbox" in params else
+ Bbox.from_bounds(-params["xdescent"], -params["ydescent"],
+ params["width"], params["height"]))
+ return meth(params["self"], bbox, params["renderer"])
+ return get_offset
+
+
+@_api.deprecated("3.7", alternative='patches.bbox_artist')
+def bbox_artist(*args, **kwargs):
+ if DEBUG:
+ mbbox_artist(*args, **kwargs)
+
+
+# for debugging use
+def _bbox_artist(*args, **kwargs):
+ if DEBUG:
+ mbbox_artist(*args, **kwargs)
+
+
+def _get_packed_offsets(widths, total, sep, mode="fixed"):
+ r"""
+ Pack boxes specified by their *widths*.
+
+ For simplicity of the description, the terminology used here assumes a
+ horizontal layout, but the function works equally for a vertical layout.
+
+ There are three packing *mode*\s:
+
+ - 'fixed': The elements are packed tight to the left with a spacing of
+ *sep* in between. If *total* is *None* the returned total will be the
+ right edge of the last box. A non-*None* total will be passed unchecked
+ to the output. In particular this means that right edge of the last
+ box may be further to the right than the returned total.
+
+ - 'expand': Distribute the boxes with equal spacing so that the left edge
+ of the first box is at 0, and the right edge of the last box is at
+ *total*. The parameter *sep* is ignored in this mode. A total of *None*
+ is accepted and considered equal to 1. The total is returned unchanged
+ (except for the conversion *None* to 1). If the total is smaller than
+ the sum of the widths, the laid out boxes will overlap.
+
+ - 'equal': If *total* is given, the total space is divided in N equal
+ ranges and each box is left-aligned within its subspace.
+ Otherwise (*total* is *None*), *sep* must be provided and each box is
+ left-aligned in its subspace of width ``(max(widths) + sep)``. The
+ total width is then calculated to be ``N * (max(widths) + sep)``.
+
+ Parameters
+ ----------
+ widths : list of float
+ Widths of boxes to be packed.
+ total : float or None
+ Intended total length. *None* if not used.
+ sep : float
+ Spacing between boxes.
+ mode : {'fixed', 'expand', 'equal'}
+ The packing mode.
+
+ Returns
+ -------
+ total : float
+ The total width needed to accommodate the laid out boxes.
+ offsets : array of float
+ The left offsets of the boxes.
+ """
+ _api.check_in_list(["fixed", "expand", "equal"], mode=mode)
+
+ if mode == "fixed":
+ offsets_ = np.cumsum([0] + [w + sep for w in widths])
+ offsets = offsets_[:-1]
+ if total is None:
+ total = offsets_[-1] - sep
+ return total, offsets
+
+ elif mode == "expand":
+ # This is a bit of a hack to avoid a TypeError when *total*
+ # is None and used in conjugation with tight layout.
+ if total is None:
+ total = 1
+ if len(widths) > 1:
+ sep = (total - sum(widths)) / (len(widths) - 1)
+ else:
+ sep = 0
+ offsets_ = np.cumsum([0] + [w + sep for w in widths])
+ offsets = offsets_[:-1]
+ return total, offsets
+
+ elif mode == "equal":
+ maxh = max(widths)
+ if total is None:
+ if sep is None:
+ raise ValueError("total and sep cannot both be None when "
+ "using layout mode 'equal'")
+ total = (maxh + sep) * len(widths)
+ else:
+ sep = total / len(widths) - maxh
+ offsets = (maxh + sep) * np.arange(len(widths))
+ return total, offsets
+
+
+def _get_aligned_offsets(yspans, height, align="baseline"):
+ """
+ Align boxes each specified by their ``(y0, y1)`` spans.
+
+ For simplicity of the description, the terminology used here assumes a
+ horizontal layout (i.e., vertical alignment), but the function works
+ equally for a vertical layout.
+
+ Parameters
+ ----------
+ yspans
+ List of (y0, y1) spans of boxes to be aligned.
+ height : float or None
+ Intended total height. If None, the maximum of the heights
+ (``y1 - y0``) in *yspans* is used.
+ align : {'baseline', 'left', 'top', 'right', 'bottom', 'center'}
+ The alignment anchor of the boxes.
+
+ Returns
+ -------
+ (y0, y1)
+ y range spanned by the packing. If a *height* was originally passed
+ in, then for all alignments other than "baseline", a span of ``(0,
+ height)`` is used without checking that it is actually large enough).
+ descent
+ The descent of the packing.
+ offsets
+ The bottom offsets of the boxes.
+ """
+
+ _api.check_in_list(
+ ["baseline", "left", "top", "right", "bottom", "center"], align=align)
+ if height is None:
+ height = max(y1 - y0 for y0, y1 in yspans)
+
+ if align == "baseline":
+ yspan = (min(y0 for y0, y1 in yspans), max(y1 for y0, y1 in yspans))
+ offsets = [0] * len(yspans)
+ elif align in ["left", "bottom"]:
+ yspan = (0, height)
+ offsets = [-y0 for y0, y1 in yspans]
+ elif align in ["right", "top"]:
+ yspan = (0, height)
+ offsets = [height - y1 for y0, y1 in yspans]
+ elif align == "center":
+ yspan = (0, height)
+ offsets = [(height - (y1 - y0)) * .5 - y0 for y0, y1 in yspans]
+
+ return yspan, offsets
+
+
+class OffsetBox(martist.Artist):
+ """
+ The OffsetBox is a simple container artist.
+
+ The child artists are meant to be drawn at a relative position to its
+ parent.
+
+ Being an artist itself, all parameters are passed on to `.Artist`.
+ """
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args)
+ self._internal_update(kwargs)
+ # Clipping has not been implemented in the OffsetBox family, so
+ # disable the clip flag for consistency. It can always be turned back
+ # on to zero effect.
+ self.set_clip_on(False)
+ self._children = []
+ self._offset = (0, 0)
+
+ def set_figure(self, fig):
+ """
+ Set the `.Figure` for the `.OffsetBox` and all its children.
+
+ Parameters
+ ----------
+ fig : `~matplotlib.figure.Figure`
+ """
+ super().set_figure(fig)
+ for c in self.get_children():
+ c.set_figure(fig)
+
+ @martist.Artist.axes.setter
+ def axes(self, ax):
+ # TODO deal with this better
+ martist.Artist.axes.fset(self, ax)
+ for c in self.get_children():
+ if c is not None:
+ c.axes = ax
+
+ def contains(self, mouseevent):
+ """
+ Delegate the mouse event contains-check to the children.
+
+ As a container, the `.OffsetBox` does not respond itself to
+ mouseevents.
+
+ Parameters
+ ----------
+ mouseevent : `~matplotlib.backend_bases.MouseEvent`
+
+ Returns
+ -------
+ contains : bool
+ Whether any values are within the radius.
+ details : dict
+ An artist-specific dictionary of details of the event context,
+ such as which points are contained in the pick radius. See the
+ individual Artist subclasses for details.
+
+ See Also
+ --------
+ .Artist.contains
+ """
+ inside, info = self._default_contains(mouseevent)
+ if inside is not None:
+ return inside, info
+ for c in self.get_children():
+ a, b = c.contains(mouseevent)
+ if a:
+ return a, b
+ return False, {}
+
+ def set_offset(self, xy):
+ """
+ Set the offset.
+
+ Parameters
+ ----------
+ xy : (float, float) or callable
+ The (x, y) coordinates of the offset in display units. These can
+ either be given explicitly as a tuple (x, y), or by providing a
+ function that converts the extent into the offset. This function
+ must have the signature::
+
+ def offset(width, height, xdescent, ydescent, renderer) \
+-> (float, float)
+ """
+ self._offset = xy
+ self.stale = True
+
+ @_compat_get_offset
+ def get_offset(self, bbox, renderer):
+ """
+ Return the offset as a tuple (x, y).
+
+ The extent parameters have to be provided to handle the case where the
+ offset is dynamically determined by a callable (see
+ `~.OffsetBox.set_offset`).
+
+ Parameters
+ ----------
+ bbox : `.Bbox`
+ renderer : `.RendererBase` subclass
+ """
+ return (
+ self._offset(bbox.width, bbox.height, -bbox.x0, -bbox.y0, renderer)
+ if callable(self._offset)
+ else self._offset)
+
+ def set_width(self, width):
+ """
+ Set the width of the box.
+
+ Parameters
+ ----------
+ width : float
+ """
+ self.width = width
+ self.stale = True
+
+ def set_height(self, height):
+ """
+ Set the height of the box.
+
+ Parameters
+ ----------
+ height : float
+ """
+ self.height = height
+ self.stale = True
+
+ def get_visible_children(self):
+ r"""Return a list of the visible child `.Artist`\s."""
+ return [c for c in self._children if c.get_visible()]
+
+ def get_children(self):
+ r"""Return a list of the child `.Artist`\s."""
+ return self._children
+
+ def _get_bbox_and_child_offsets(self, renderer):
+ """
+ Return the bbox of the offsetbox and the child offsets.
+
+ The bbox should satisfy ``x0 <= x1 and y0 <= y1``.
+
+ Parameters
+ ----------
+ renderer : `.RendererBase` subclass
+
+ Returns
+ -------
+ bbox
+ list of (xoffset, yoffset) pairs
+ """
+ raise NotImplementedError(
+ "get_bbox_and_offsets must be overridden in derived classes")
+
+ def get_bbox(self, renderer):
+ """Return the bbox of the offsetbox, ignoring parent offsets."""
+ bbox, offsets = self._get_bbox_and_child_offsets(renderer)
+ return bbox
+
+ @_api.deprecated("3.7", alternative="get_bbox and child.get_offset")
+ def get_extent_offsets(self, renderer):
+ """
+ Update offset of the children and return the extent of the box.
+
+ Parameters
+ ----------
+ renderer : `.RendererBase` subclass
+
+ Returns
+ -------
+ width
+ height
+ xdescent
+ ydescent
+ list of (xoffset, yoffset) pairs
+ """
+ bbox, offsets = self._get_bbox_and_child_offsets(renderer)
+ return bbox.width, bbox.height, -bbox.x0, -bbox.y0, offsets
+
+ @_api.deprecated("3.7", alternative="get_bbox")
+ def get_extent(self, renderer):
+ """Return a tuple ``width, height, xdescent, ydescent`` of the box."""
+ bbox = self.get_bbox(renderer)
+ return bbox.width, bbox.height, -bbox.x0, -bbox.y0
+
+ def get_window_extent(self, renderer=None):
+ # docstring inherited
+ if renderer is None:
+ renderer = self.figure._get_renderer()
+ bbox = self.get_bbox(renderer)
+ try: # Some subclasses redefine get_offset to take no args.
+ px, py = self.get_offset(bbox, renderer)
+ except TypeError:
+ px, py = self.get_offset()
+ return bbox.translated(px, py)
+
+ def draw(self, renderer):
+ """
+ Update the location of children if necessary and draw them
+ to the given *renderer*.
+ """
+ bbox, offsets = self._get_bbox_and_child_offsets(renderer)
+ px, py = self.get_offset(bbox, renderer)
+ for c, (ox, oy) in zip(self.get_visible_children(), offsets):
+ c.set_offset((px + ox, py + oy))
+ c.draw(renderer)
+ _bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
+ self.stale = False
+
+
+class PackerBase(OffsetBox):
+ def __init__(self, pad=0., sep=0., width=None, height=None,
+ align="baseline", mode="fixed", children=None):
+ """
+ Parameters
+ ----------
+ pad : float, default: 0.0
+ The boundary padding in points.
+
+ sep : float, default: 0.0
+ The spacing between items in points.
+
+ width, height : float, optional
+ Width and height of the container box in pixels, calculated if
+ *None*.
+
+ align : {'top', 'bottom', 'left', 'right', 'center', 'baseline'}, \
+default: 'baseline'
+ Alignment of boxes.
+
+ mode : {'fixed', 'expand', 'equal'}, default: 'fixed'
+ The packing mode.
+
+ - 'fixed' packs the given `.Artist`\\s tight with *sep* spacing.
+ - 'expand' uses the maximal available space to distribute the
+ artists with equal spacing in between.
+ - 'equal': Each artist an equal fraction of the available space
+ and is left-aligned (or top-aligned) therein.
+
+ children : list of `.Artist`
+ The artists to pack.
+
+ Notes
+ -----
+ *pad* and *sep* are in points and will be scaled with the renderer
+ dpi, while *width* and *height* are in pixels.
+ """
+ super().__init__()
+ self.height = height
+ self.width = width
+ self.sep = sep
+ self.pad = pad
+ self.mode = mode
+ self.align = align
+ self._children = children
+
+
+class VPacker(PackerBase):
+ """
+ VPacker packs its children vertically, automatically adjusting their
+ relative positions at draw time.
+ """
+
+ def _get_bbox_and_child_offsets(self, renderer):
+ # docstring inherited
+ dpicor = renderer.points_to_pixels(1.)
+ pad = self.pad * dpicor
+ sep = self.sep * dpicor
+
+ if self.width is not None:
+ for c in self.get_visible_children():
+ if isinstance(c, PackerBase) and c.mode == "expand":
+ c.set_width(self.width)
+
+ bboxes = [c.get_bbox(renderer) for c in self.get_visible_children()]
+ (x0, x1), xoffsets = _get_aligned_offsets(
+ [bbox.intervalx for bbox in bboxes], self.width, self.align)
+ height, yoffsets = _get_packed_offsets(
+ [bbox.height for bbox in bboxes], self.height, sep, self.mode)
+
+ yoffsets = height - (yoffsets + [bbox.y1 for bbox in bboxes])
+ ydescent = yoffsets[0]
+ yoffsets = yoffsets - ydescent
+
+ return (
+ Bbox.from_bounds(x0, -ydescent, x1 - x0, height).padded(pad),
+ [*zip(xoffsets, yoffsets)])
+
+
+class HPacker(PackerBase):
+ """
+ HPacker packs its children horizontally, automatically adjusting their
+ relative positions at draw time.
+ """
+
+ def _get_bbox_and_child_offsets(self, renderer):
+ # docstring inherited
+ dpicor = renderer.points_to_pixels(1.)
+ pad = self.pad * dpicor
+ sep = self.sep * dpicor
+
+ bboxes = [c.get_bbox(renderer) for c in self.get_visible_children()]
+ if not bboxes:
+ return Bbox.from_bounds(0, 0, 0, 0).padded(pad), []
+
+ (y0, y1), yoffsets = _get_aligned_offsets(
+ [bbox.intervaly for bbox in bboxes], self.height, self.align)
+ width, xoffsets = _get_packed_offsets(
+ [bbox.width for bbox in bboxes], self.width, sep, self.mode)
+
+ x0 = bboxes[0].x0
+ xoffsets -= ([bbox.x0 for bbox in bboxes] - x0)
+
+ return (Bbox.from_bounds(x0, y0, width, y1 - y0).padded(pad),
+ [*zip(xoffsets, yoffsets)])
+
+
+class PaddedBox(OffsetBox):
+ """
+ A container to add a padding around an `.Artist`.
+
+ The `.PaddedBox` contains a `.FancyBboxPatch` that is used to visualize
+ it when rendering.
+ """
+
+ @_api.make_keyword_only("3.6", name="draw_frame")
+ def __init__(self, child, pad=0., draw_frame=False, patch_attrs=None):
+ """
+ Parameters
+ ----------
+ child : `~matplotlib.artist.Artist`
+ The contained `.Artist`.
+ pad : float, default: 0.0
+ The padding in points. This will be scaled with the renderer dpi.
+ In contrast, *width* and *height* are in *pixels* and thus not
+ scaled.
+ draw_frame : bool
+ Whether to draw the contained `.FancyBboxPatch`.
+ patch_attrs : dict or None
+ Additional parameters passed to the contained `.FancyBboxPatch`.
+ """
+ super().__init__()
+ self.pad = pad
+ self._children = [child]
+ self.patch = FancyBboxPatch(
+ xy=(0.0, 0.0), width=1., height=1.,
+ facecolor='w', edgecolor='k',
+ mutation_scale=1, # self.prop.get_size_in_points(),
+ snap=True,
+ visible=draw_frame,
+ boxstyle="square,pad=0",
+ )
+ if patch_attrs is not None:
+ self.patch.update(patch_attrs)
+
+ def _get_bbox_and_child_offsets(self, renderer):
+ # docstring inherited.
+ pad = self.pad * renderer.points_to_pixels(1.)
+ return (self._children[0].get_bbox(renderer).padded(pad), [(0, 0)])
+
+ def draw(self, renderer):
+ # docstring inherited
+ bbox, offsets = self._get_bbox_and_child_offsets(renderer)
+ px, py = self.get_offset(bbox, renderer)
+ for c, (ox, oy) in zip(self.get_visible_children(), offsets):
+ c.set_offset((px + ox, py + oy))
+
+ self.draw_frame(renderer)
+
+ for c in self.get_visible_children():
+ c.draw(renderer)
+
+ self.stale = False
+
+ def update_frame(self, bbox, fontsize=None):
+ self.patch.set_bounds(bbox.bounds)
+ if fontsize:
+ self.patch.set_mutation_scale(fontsize)
+ self.stale = True
+
+ def draw_frame(self, renderer):
+ # update the location and size of the legend
+ self.update_frame(self.get_window_extent(renderer))
+ self.patch.draw(renderer)
+
+
+class DrawingArea(OffsetBox):
+ """
+ The DrawingArea can contain any Artist as a child. The DrawingArea
+ has a fixed width and height. The position of children relative to
+ the parent is fixed. The children can be clipped at the
+ boundaries of the parent.
+ """
+
+ def __init__(self, width, height, xdescent=0., ydescent=0., clip=False):
+ """
+ Parameters
+ ----------
+ width, height : float
+ Width and height of the container box.
+ xdescent, ydescent : float
+ Descent of the box in x- and y-direction.
+ clip : bool
+ Whether to clip the children to the box.
+ """
+ super().__init__()
+ self.width = width
+ self.height = height
+ self.xdescent = xdescent
+ self.ydescent = ydescent
+ self._clip_children = clip
+ self.offset_transform = mtransforms.Affine2D()
+ self.dpi_transform = mtransforms.Affine2D()
+
+ @property
+ def clip_children(self):
+ """
+ If the children of this DrawingArea should be clipped
+ by DrawingArea bounding box.
+ """
+ return self._clip_children
+
+ @clip_children.setter
+ def clip_children(self, val):
+ self._clip_children = bool(val)
+ self.stale = True
+
+ def get_transform(self):
+ """
+ Return the `~matplotlib.transforms.Transform` applied to the children.
+ """
+ return self.dpi_transform + self.offset_transform
+
+ def set_transform(self, t):
+ """
+ set_transform is ignored.
+ """
+
+ def set_offset(self, xy):
+ """
+ Set the offset of the container.
+
+ Parameters
+ ----------
+ xy : (float, float)
+ The (x, y) coordinates of the offset in display units.
+ """
+ self._offset = xy
+ self.offset_transform.clear()
+ self.offset_transform.translate(xy[0], xy[1])
+ self.stale = True
+
+ def get_offset(self):
+ """Return offset of the container."""
+ return self._offset
+
+ def get_bbox(self, renderer):
+ # docstring inherited
+ dpi_cor = renderer.points_to_pixels(1.)
+ return Bbox.from_bounds(
+ -self.xdescent * dpi_cor, -self.ydescent * dpi_cor,
+ self.width * dpi_cor, self.height * dpi_cor)
+
+ def add_artist(self, a):
+ """Add an `.Artist` to the container box."""
+ self._children.append(a)
+ if not a.is_transform_set():
+ a.set_transform(self.get_transform())
+ if self.axes is not None:
+ a.axes = self.axes
+ fig = self.figure
+ if fig is not None:
+ a.set_figure(fig)
+
+ def draw(self, renderer):
+ # docstring inherited
+
+ dpi_cor = renderer.points_to_pixels(1.)
+ self.dpi_transform.clear()
+ self.dpi_transform.scale(dpi_cor)
+
+ # At this point the DrawingArea has a transform
+ # to the display space so the path created is
+ # good for clipping children
+ tpath = mtransforms.TransformedPath(
+ mpath.Path([[0, 0], [0, self.height],
+ [self.width, self.height],
+ [self.width, 0]]),
+ self.get_transform())
+ for c in self._children:
+ if self._clip_children and not (c.clipbox or c._clippath):
+ c.set_clip_path(tpath)
+ c.draw(renderer)
+
+ _bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
+ self.stale = False
+
+
+class TextArea(OffsetBox):
+ """
+ The TextArea is a container artist for a single Text instance.
+
+ The text is placed at (0, 0) with baseline+left alignment, by default. The
+ width and height of the TextArea instance is the width and height of its
+ child text.
+ """
+
+ @_api.make_keyword_only("3.6", name="textprops")
+ def __init__(self, s,
+ textprops=None,
+ multilinebaseline=False,
+ ):
+ """
+ Parameters
+ ----------
+ s : str
+ The text to be displayed.
+ textprops : dict, default: {}
+ Dictionary of keyword parameters to be passed to the `.Text`
+ instance in the TextArea.
+ multilinebaseline : bool, default: False
+ Whether the baseline for multiline text is adjusted so that it
+ is (approximately) center-aligned with single-line text.
+ """
+ if textprops is None:
+ textprops = {}
+ self._text = mtext.Text(0, 0, s, **textprops)
+ super().__init__()
+ self._children = [self._text]
+ self.offset_transform = mtransforms.Affine2D()
+ self._baseline_transform = mtransforms.Affine2D()
+ self._text.set_transform(self.offset_transform +
+ self._baseline_transform)
+ self._multilinebaseline = multilinebaseline
+
+ def set_text(self, s):
+ """Set the text of this area as a string."""
+ self._text.set_text(s)
+ self.stale = True
+
+ def get_text(self):
+ """Return the string representation of this area's text."""
+ return self._text.get_text()
+
+ def set_multilinebaseline(self, t):
+ """
+ Set multilinebaseline.
+
+ If True, the baseline for multiline text is adjusted so that it is
+ (approximately) center-aligned with single-line text. This is used
+ e.g. by the legend implementation so that single-line labels are
+ baseline-aligned, but multiline labels are "center"-aligned with them.
+ """
+ self._multilinebaseline = t
+ self.stale = True
+
+ def get_multilinebaseline(self):
+ """
+ Get multilinebaseline.
+ """
+ return self._multilinebaseline
+
+ def set_transform(self, t):
+ """
+ set_transform is ignored.
+ """
+
+ def set_offset(self, xy):
+ """
+ Set the offset of the container.
+
+ Parameters
+ ----------
+ xy : (float, float)
+ The (x, y) coordinates of the offset in display units.
+ """
+ self._offset = xy
+ self.offset_transform.clear()
+ self.offset_transform.translate(xy[0], xy[1])
+ self.stale = True
+
+ def get_offset(self):
+ """Return offset of the container."""
+ return self._offset
+
+ def get_bbox(self, renderer):
+ _, h_, d_ = renderer.get_text_width_height_descent(
+ "lp", self._text._fontproperties,
+ ismath="TeX" if self._text.get_usetex() else False)
+
+ bbox, info, yd = self._text._get_layout(renderer)
+ w, h = bbox.size
+
+ self._baseline_transform.clear()
+
+ if len(info) > 1 and self._multilinebaseline:
+ yd_new = 0.5 * h - 0.5 * (h_ - d_)
+ self._baseline_transform.translate(0, yd - yd_new)
+ yd = yd_new
+ else: # single line
+ h_d = max(h_ - d_, h - yd)
+ h = h_d + yd
+
+ ha = self._text.get_horizontalalignment()
+ x0 = {"left": 0, "center": -w / 2, "right": -w}[ha]
+
+ return Bbox.from_bounds(x0, -yd, w, h)
+
+ def draw(self, renderer):
+ # docstring inherited
+ self._text.draw(renderer)
+ _bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
+ self.stale = False
+
+
+class AuxTransformBox(OffsetBox):
+ """
+ Offset Box with the aux_transform. Its children will be
+ transformed with the aux_transform first then will be
+ offsetted. The absolute coordinate of the aux_transform is meaning
+ as it will be automatically adjust so that the left-lower corner
+ of the bounding box of children will be set to (0, 0) before the
+ offset transform.
+
+ It is similar to drawing area, except that the extent of the box
+ is not predetermined but calculated from the window extent of its
+ children. Furthermore, the extent of the children will be
+ calculated in the transformed coordinate.
+ """
+ def __init__(self, aux_transform):
+ self.aux_transform = aux_transform
+ super().__init__()
+ self.offset_transform = mtransforms.Affine2D()
+ # ref_offset_transform makes offset_transform always relative to the
+ # lower-left corner of the bbox of its children.
+ self.ref_offset_transform = mtransforms.Affine2D()
+
+ def add_artist(self, a):
+ """Add an `.Artist` to the container box."""
+ self._children.append(a)
+ a.set_transform(self.get_transform())
+ self.stale = True
+
+ def get_transform(self):
+ """
+ Return the :class:`~matplotlib.transforms.Transform` applied
+ to the children
+ """
+ return (self.aux_transform
+ + self.ref_offset_transform
+ + self.offset_transform)
+
+ def set_transform(self, t):
+ """
+ set_transform is ignored.
+ """
+
+ def set_offset(self, xy):
+ """
+ Set the offset of the container.
+
+ Parameters
+ ----------
+ xy : (float, float)
+ The (x, y) coordinates of the offset in display units.
+ """
+ self._offset = xy
+ self.offset_transform.clear()
+ self.offset_transform.translate(xy[0], xy[1])
+ self.stale = True
+
+ def get_offset(self):
+ """Return offset of the container."""
+ return self._offset
+
+ def get_bbox(self, renderer):
+ # clear the offset transforms
+ _off = self.offset_transform.get_matrix() # to be restored later
+ self.ref_offset_transform.clear()
+ self.offset_transform.clear()
+ # calculate the extent
+ bboxes = [c.get_window_extent(renderer) for c in self._children]
+ ub = Bbox.union(bboxes)
+ # adjust ref_offset_transform
+ self.ref_offset_transform.translate(-ub.x0, -ub.y0)
+ # restore offset transform
+ self.offset_transform.set_matrix(_off)
+ return Bbox.from_bounds(0, 0, ub.width, ub.height)
+
+ def draw(self, renderer):
+ # docstring inherited
+ for c in self._children:
+ c.draw(renderer)
+ _bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
+ self.stale = False
+
+
+class AnchoredOffsetbox(OffsetBox):
+ """
+ An offset box placed according to location *loc*.
+
+ AnchoredOffsetbox has a single child. When multiple children are needed,
+ use an extra OffsetBox to enclose them. By default, the offset box is
+ anchored against its parent axes. You may explicitly specify the
+ *bbox_to_anchor*.
+ """
+ zorder = 5 # zorder of the legend
+
+ # Location codes
+ codes = {'upper right': 1,
+ 'upper left': 2,
+ 'lower left': 3,
+ 'lower right': 4,
+ 'right': 5,
+ 'center left': 6,
+ 'center right': 7,
+ 'lower center': 8,
+ 'upper center': 9,
+ 'center': 10,
+ }
+
+ @_api.make_keyword_only("3.6", name="pad")
+ def __init__(self, loc,
+ pad=0.4, borderpad=0.5,
+ child=None, prop=None, frameon=True,
+ bbox_to_anchor=None,
+ bbox_transform=None,
+ **kwargs):
+ """
+ Parameters
+ ----------
+ loc : str
+ The box location. Valid locations are
+ 'upper left', 'upper center', 'upper right',
+ 'center left', 'center', 'center right',
+ 'lower left', 'lower center', 'lower right'.
+ For backward compatibility, numeric values are accepted as well.
+ See the parameter *loc* of `.Legend` for details.
+ pad : float, default: 0.4
+ Padding around the child as fraction of the fontsize.
+ borderpad : float, default: 0.5
+ Padding between the offsetbox frame and the *bbox_to_anchor*.
+ child : `.OffsetBox`
+ The box that will be anchored.
+ prop : `.FontProperties`
+ This is only used as a reference for paddings. If not given,
+ :rc:`legend.fontsize` is used.
+ frameon : bool
+ Whether to draw a frame around the box.
+ bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats
+ Box that is used to position the legend in conjunction with *loc*.
+ bbox_transform : None or :class:`matplotlib.transforms.Transform`
+ The transform for the bounding box (*bbox_to_anchor*).
+ **kwargs
+ All other parameters are passed on to `.OffsetBox`.
+
+ Notes
+ -----
+ See `.Legend` for a detailed description of the anchoring mechanism.
+ """
+ super().__init__(**kwargs)
+
+ self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
+ self.set_child(child)
+
+ if isinstance(loc, str):
+ loc = _api.check_getitem(self.codes, loc=loc)
+
+ self.loc = loc
+ self.borderpad = borderpad
+ self.pad = pad
+
+ if prop is None:
+ 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(mpl.rcParams["legend.fontsize"])
+
+ self.patch = FancyBboxPatch(
+ xy=(0.0, 0.0), width=1., height=1.,
+ facecolor='w', edgecolor='k',
+ mutation_scale=self.prop.get_size_in_points(),
+ snap=True,
+ visible=frameon,
+ boxstyle="square,pad=0",
+ )
+
+ def set_child(self, child):
+ """Set the child to be anchored."""
+ self._child = child
+ if child is not None:
+ child.axes = self.axes
+ self.stale = True
+
+ def get_child(self):
+ """Return the child."""
+ return self._child
+
+ def get_children(self):
+ """Return the list of children."""
+ return [self._child]
+
+ def get_bbox(self, renderer):
+ # docstring inherited
+ fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
+ pad = self.pad * fontsize
+ return self.get_child().get_bbox(renderer).padded(pad)
+
+ def get_bbox_to_anchor(self):
+ """Return the bbox that the box is anchored to."""
+ if self._bbox_to_anchor is None:
+ return self.axes.bbox
+ else:
+ transform = self._bbox_to_anchor_transform
+ if transform is None:
+ return self._bbox_to_anchor
+ else:
+ return TransformedBbox(self._bbox_to_anchor, transform)
+
+ def set_bbox_to_anchor(self, bbox, transform=None):
+ """
+ Set the bbox that the box is anchored to.
+
+ *bbox* can be a Bbox instance, a list of [left, bottom, width,
+ height], or a list of [left, bottom] where the width and
+ height will be assumed to be zero. The bbox will be
+ transformed to display coordinate by the given transform.
+ """
+ if bbox is None or isinstance(bbox, BboxBase):
+ self._bbox_to_anchor = bbox
+ else:
+ try:
+ l = len(bbox)
+ except TypeError as err:
+ raise ValueError(f"Invalid bbox: {bbox}") from err
+
+ if l == 2:
+ bbox = [bbox[0], bbox[1], 0, 0]
+
+ self._bbox_to_anchor = Bbox.from_bounds(*bbox)
+
+ self._bbox_to_anchor_transform = transform
+ self.stale = True
+
+ @_compat_get_offset
+ def get_offset(self, bbox, renderer):
+ # docstring inherited
+ pad = (self.borderpad
+ * renderer.points_to_pixels(self.prop.get_size_in_points()))
+ bbox_to_anchor = self.get_bbox_to_anchor()
+ x0, y0 = _get_anchored_bbox(
+ self.loc, Bbox.from_bounds(0, 0, bbox.width, bbox.height),
+ bbox_to_anchor, pad)
+ return x0 - bbox.x0, y0 - bbox.y0
+
+ def update_frame(self, bbox, fontsize=None):
+ self.patch.set_bounds(bbox.bounds)
+ if fontsize:
+ self.patch.set_mutation_scale(fontsize)
+
+ def draw(self, renderer):
+ # docstring inherited
+ if not self.get_visible():
+ return
+
+ # update the location and size of the legend
+ bbox = self.get_window_extent(renderer)
+ fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
+ self.update_frame(bbox, fontsize)
+ self.patch.draw(renderer)
+
+ px, py = self.get_offset(self.get_bbox(renderer), renderer)
+ self.get_child().set_offset((px, py))
+ self.get_child().draw(renderer)
+ self.stale = False
+
+
+def _get_anchored_bbox(loc, bbox, parentbbox, borderpad):
+ """
+ Return the (x, y) position of the *bbox* anchored at the *parentbbox* with
+ the *loc* code with the *borderpad*.
+ """
+ # This is only called internally and *loc* should already have been
+ # validated. If 0 (None), we just let ``bbox.anchored`` raise.
+ c = [None, "NE", "NW", "SW", "SE", "E", "W", "E", "S", "N", "C"][loc]
+ container = parentbbox.padded(-borderpad)
+ return bbox.anchored(c, container=container).p0
+
+
+class AnchoredText(AnchoredOffsetbox):
+ """
+ AnchoredOffsetbox with Text.
+ """
+
+ @_api.make_keyword_only("3.6", name="pad")
+ def __init__(self, s, loc, pad=0.4, borderpad=0.5, prop=None, **kwargs):
+ """
+ Parameters
+ ----------
+ s : str
+ Text.
+
+ loc : str
+ Location code. See `AnchoredOffsetbox`.
+
+ pad : float, default: 0.4
+ Padding around the text as fraction of the fontsize.
+
+ borderpad : float, default: 0.5
+ Spacing between the offsetbox frame and the *bbox_to_anchor*.
+
+ prop : dict, optional
+ Dictionary of keyword parameters to be passed to the
+ `~matplotlib.text.Text` instance contained inside AnchoredText.
+
+ **kwargs
+ All other parameters are passed to `AnchoredOffsetbox`.
+ """
+
+ if prop is None:
+ prop = {}
+ badkwargs = {'va', 'verticalalignment'}
+ if badkwargs & set(prop):
+ raise ValueError(
+ 'Mixing verticalalignment with AnchoredText is not supported.')
+
+ self.txt = TextArea(s, textprops=prop)
+ fp = self.txt._text.get_fontproperties()
+ super().__init__(
+ loc, pad=pad, borderpad=borderpad, child=self.txt, prop=fp,
+ **kwargs)
+
+
+class OffsetImage(OffsetBox):
+
+ @_api.make_keyword_only("3.6", name="zoom")
+ def __init__(self, arr,
+ zoom=1,
+ cmap=None,
+ norm=None,
+ interpolation=None,
+ origin=None,
+ filternorm=True,
+ filterrad=4.0,
+ resample=False,
+ dpi_cor=True,
+ **kwargs
+ ):
+
+ super().__init__()
+ self._dpi_cor = dpi_cor
+
+ self.image = BboxImage(bbox=self.get_window_extent,
+ cmap=cmap,
+ norm=norm,
+ interpolation=interpolation,
+ origin=origin,
+ filternorm=filternorm,
+ filterrad=filterrad,
+ resample=resample,
+ **kwargs
+ )
+
+ self._children = [self.image]
+
+ self.set_zoom(zoom)
+ self.set_data(arr)
+
+ def set_data(self, arr):
+ self._data = np.asarray(arr)
+ self.image.set_data(self._data)
+ self.stale = True
+
+ def get_data(self):
+ return self._data
+
+ def set_zoom(self, zoom):
+ self._zoom = zoom
+ self.stale = True
+
+ def get_zoom(self):
+ return self._zoom
+
+ def get_offset(self):
+ """Return offset of the container."""
+ return self._offset
+
+ def get_children(self):
+ return [self.image]
+
+ def get_bbox(self, renderer):
+ dpi_cor = renderer.points_to_pixels(1.) if self._dpi_cor else 1.
+ zoom = self.get_zoom()
+ data = self.get_data()
+ ny, nx = data.shape[:2]
+ w, h = dpi_cor * nx * zoom, dpi_cor * ny * zoom
+ return Bbox.from_bounds(0, 0, w, h)
+
+ def draw(self, renderer):
+ # docstring inherited
+ self.image.draw(renderer)
+ # bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
+ self.stale = False
+
+
+class AnnotationBbox(martist.Artist, mtext._AnnotationBase):
+ """
+ Container for an `OffsetBox` referring to a specific position *xy*.
+
+ Optionally an arrow pointing from the offsetbox to *xy* can be drawn.
+
+ This is like `.Annotation`, but with `OffsetBox` instead of `.Text`.
+ """
+
+ zorder = 3
+
+ def __str__(self):
+ return "AnnotationBbox(%g,%g)" % (self.xy[0], self.xy[1])
+
+ @_docstring.dedent_interpd
+ @_api.make_keyword_only("3.6", name="xycoords")
+ def __init__(self, offsetbox, xy,
+ xybox=None,
+ xycoords='data',
+ boxcoords=None,
+ frameon=True, pad=0.4, # FancyBboxPatch boxstyle.
+ annotation_clip=None,
+ box_alignment=(0.5, 0.5),
+ bboxprops=None,
+ arrowprops=None,
+ fontsize=None,
+ **kwargs):
+ """
+ Parameters
+ ----------
+ offsetbox : `OffsetBox`
+
+ xy : (float, float)
+ The point *(x, y)* to annotate. The coordinate system is determined
+ by *xycoords*.
+
+ xybox : (float, float), default: *xy*
+ The position *(x, y)* to place the text at. The coordinate system
+ is determined by *boxcoords*.
+
+ xycoords : single or two-tuple of str or `.Artist` or `.Transform` or \
+callable, default: 'data'
+ The coordinate system that *xy* is given in. See the parameter
+ *xycoords* in `.Annotation` for a detailed description.
+
+ boxcoords : single or two-tuple of str or `.Artist` or `.Transform` \
+or callable, default: value of *xycoords*
+ The coordinate system that *xybox* is given in. See the parameter
+ *textcoords* in `.Annotation` for a detailed description.
+
+ frameon : bool, default: True
+ By default, the text is surrounded by a white `.FancyBboxPatch`
+ (accessible as the ``patch`` attribute of the `.AnnotationBbox`).
+ If *frameon* is set to False, this patch is made invisible.
+
+ annotation_clip: bool or None, default: None
+ Whether to clip (i.e. not draw) the annotation when the annotation
+ point *xy* is outside the axes area.
+
+ - If *True*, the annotation will be clipped when *xy* is outside
+ the axes.
+ - If *False*, the annotation will always be drawn.
+ - If *None*, the annotation will be clipped when *xy* is outside
+ the axes and *xycoords* is 'data'.
+
+ pad : float, default: 0.4
+ Padding around the offsetbox.
+
+ box_alignment : (float, float)
+ A tuple of two floats for a vertical and horizontal alignment of
+ the offset box w.r.t. the *boxcoords*.
+ The lower-left corner is (0, 0) and upper-right corner is (1, 1).
+
+ bboxprops : dict, optional
+ A dictionary of properties to set for the annotation bounding box,
+ for example *boxstyle* and *alpha*. See `.FancyBboxPatch` for
+ details.
+
+ arrowprops: dict, optional
+ Arrow properties, see `.Annotation` for description.
+
+ fontsize: float or str, optional
+ Translated to points and passed as *mutation_scale* into
+ `.FancyBboxPatch` to scale attributes of the box style (e.g. pad
+ or rounding_size). The name is chosen in analogy to `.Text` where
+ *fontsize* defines the mutation scale as well. If not given,
+ :rc:`legend.fontsize` is used. See `.Text.set_fontsize` for valid
+ values.
+
+ **kwargs
+ Other `AnnotationBbox` properties. See `.AnnotationBbox.set` for
+ a list.
+ """
+
+ martist.Artist.__init__(self)
+ mtext._AnnotationBase.__init__(
+ self, xy, xycoords=xycoords, annotation_clip=annotation_clip)
+
+ self.offsetbox = offsetbox
+ self.arrowprops = arrowprops.copy() if arrowprops is not None else None
+ self.set_fontsize(fontsize)
+ self.xybox = xybox if xybox is not None else xy
+ self.boxcoords = boxcoords if boxcoords is not None else xycoords
+ self._box_alignment = box_alignment
+
+ if arrowprops is not None:
+ self._arrow_relpos = self.arrowprops.pop("relpos", (0.5, 0.5))
+ self.arrow_patch = FancyArrowPatch((0, 0), (1, 1),
+ **self.arrowprops)
+ else:
+ self._arrow_relpos = None
+ self.arrow_patch = None
+
+ self.patch = FancyBboxPatch( # frame
+ xy=(0.0, 0.0), width=1., height=1.,
+ facecolor='w', edgecolor='k',
+ mutation_scale=self.prop.get_size_in_points(),
+ snap=True,
+ visible=frameon,
+ )
+ self.patch.set_boxstyle("square", pad=pad)
+ if bboxprops:
+ self.patch.set(**bboxprops)
+
+ self._internal_update(kwargs)
+
+ @property
+ def xyann(self):
+ return self.xybox
+
+ @xyann.setter
+ def xyann(self, xyann):
+ self.xybox = xyann
+ self.stale = True
+
+ @property
+ def anncoords(self):
+ return self.boxcoords
+
+ @anncoords.setter
+ def anncoords(self, coords):
+ self.boxcoords = coords
+ self.stale = True
+
+ def contains(self, mouseevent):
+ inside, info = self._default_contains(mouseevent)
+ if inside is not None:
+ return inside, info
+ if not self._check_xy(None):
+ return False, {}
+ return self.offsetbox.contains(mouseevent)
+ # self.arrow_patch is currently not checked as this can be a line - JJ
+
+ def get_children(self):
+ children = [self.offsetbox, self.patch]
+ if self.arrow_patch:
+ children.append(self.arrow_patch)
+ return children
+
+ def set_figure(self, fig):
+ if self.arrow_patch is not None:
+ self.arrow_patch.set_figure(fig)
+ self.offsetbox.set_figure(fig)
+ martist.Artist.set_figure(self, fig)
+
+ def set_fontsize(self, s=None):
+ """
+ Set the fontsize in points.
+
+ If *s* is not given, reset to :rc:`legend.fontsize`.
+ """
+ if s is None:
+ s = mpl.rcParams["legend.fontsize"]
+
+ self.prop = FontProperties(size=s)
+ self.stale = True
+
+ def get_fontsize(self):
+ """Return the fontsize in points."""
+ return self.prop.get_size_in_points()
+
+ def get_window_extent(self, renderer=None):
+ # docstring inherited
+ if renderer is None:
+ renderer = self.figure._get_renderer()
+ self.update_positions(renderer)
+ return Bbox.union([child.get_window_extent(renderer)
+ for child in self.get_children()])
+
+ def get_tightbbox(self, renderer=None):
+ # docstring inherited
+ if renderer is None:
+ renderer = self.figure._get_renderer()
+ self.update_positions(renderer)
+ return Bbox.union([child.get_tightbbox(renderer)
+ for child in self.get_children()])
+
+ def update_positions(self, renderer):
+ """
+ Update pixel positions for the annotated point, the text and the arrow.
+ """
+
+ x, y = self.xybox
+ if isinstance(self.boxcoords, tuple):
+ xcoord, ycoord = self.boxcoords
+ x1, y1 = self._get_xy(renderer, x, y, xcoord)
+ x2, y2 = self._get_xy(renderer, x, y, ycoord)
+ ox0, oy0 = x1, y2
+ else:
+ ox0, oy0 = self._get_xy(renderer, x, y, self.boxcoords)
+
+ bbox = self.offsetbox.get_bbox(renderer)
+ fw, fh = self._box_alignment
+ self.offsetbox.set_offset(
+ (ox0 - fw*bbox.width - bbox.x0, oy0 - fh*bbox.height - bbox.y0))
+
+ bbox = self.offsetbox.get_window_extent(renderer)
+ self.patch.set_bounds(bbox.bounds)
+
+ mutation_scale = renderer.points_to_pixels(self.get_fontsize())
+ self.patch.set_mutation_scale(mutation_scale)
+
+ if self.arrowprops:
+ # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.
+
+ # Adjust the starting point of the arrow relative to the textbox.
+ # TODO: Rotation needs to be accounted.
+ arrow_begin = bbox.p0 + bbox.size * self._arrow_relpos
+ arrow_end = self._get_position_xy(renderer)
+ # The arrow (from arrow_begin to arrow_end) will be first clipped
+ # by patchA and patchB, then shrunk by shrinkA and shrinkB (in
+ # points). If patch A is not set, self.bbox_patch is used.
+ self.arrow_patch.set_positions(arrow_begin, arrow_end)
+
+ if "mutation_scale" in self.arrowprops:
+ mutation_scale = renderer.points_to_pixels(
+ self.arrowprops["mutation_scale"])
+ # Else, use fontsize-based mutation_scale defined above.
+ self.arrow_patch.set_mutation_scale(mutation_scale)
+
+ patchA = self.arrowprops.get("patchA", self.patch)
+ self.arrow_patch.set_patchA(patchA)
+
+ def draw(self, renderer):
+ # docstring inherited
+ if renderer is not None:
+ self._renderer = renderer
+ if not self.get_visible() or not self._check_xy(renderer):
+ return
+ renderer.open_group(self.__class__.__name__, gid=self.get_gid())
+ self.update_positions(renderer)
+ if self.arrow_patch is not None:
+ if self.arrow_patch.figure is None and self.figure is not None:
+ self.arrow_patch.figure = self.figure
+ self.arrow_patch.draw(renderer)
+ self.patch.draw(renderer)
+ self.offsetbox.draw(renderer)
+ renderer.close_group(self.__class__.__name__)
+ self.stale = False
+
+
+class DraggableBase:
+ """
+ Helper base class for a draggable artist (legend, offsetbox).
+
+ Derived classes must override the following methods::
+
+ def save_offset(self):
+ '''
+ Called when the object is picked for dragging; should save the
+ reference position of the artist.
+ '''
+
+ def update_offset(self, dx, dy):
+ '''
+ Called during the dragging; (*dx*, *dy*) is the pixel offset from
+ the point where the mouse drag started.
+ '''
+
+ Optionally, you may override the following method::
+
+ def finalize_offset(self):
+ '''Called when the mouse is released.'''
+
+ In the current implementation of `.DraggableLegend` and
+ `DraggableAnnotation`, `update_offset` places the artists in display
+ coordinates, and `finalize_offset` recalculates their position in axes
+ coordinate and set a relevant attribute.
+ """
+
+ def __init__(self, ref_artist, use_blit=False):
+ self.ref_artist = ref_artist
+ if not ref_artist.pickable():
+ ref_artist.set_picker(True)
+ self.got_artist = False
+ self._use_blit = use_blit and self.canvas.supports_blit
+ callbacks = ref_artist.figure._canvas_callbacks
+ self._disconnectors = [
+ functools.partial(
+ callbacks.disconnect, callbacks._connect_picklable(name, func))
+ for name, func in [
+ ("pick_event", self.on_pick),
+ ("button_release_event", self.on_release),
+ ("motion_notify_event", self.on_motion),
+ ]
+ ]
+
+ # A property, not an attribute, to maintain picklability.
+ canvas = property(lambda self: self.ref_artist.figure.canvas)
+
+ cids = property(lambda self: [
+ disconnect.args[0] for disconnect in self._disconnectors[:2]])
+
+ def on_motion(self, evt):
+ if self._check_still_parented() and self.got_artist:
+ dx = evt.x - self.mouse_x
+ dy = evt.y - self.mouse_y
+ self.update_offset(dx, dy)
+ if self._use_blit:
+ self.canvas.restore_region(self.background)
+ self.ref_artist.draw(
+ self.ref_artist.figure._get_renderer())
+ self.canvas.blit()
+ else:
+ self.canvas.draw()
+
+ def on_pick(self, evt):
+ if self._check_still_parented() and evt.artist == self.ref_artist:
+ self.mouse_x = evt.mouseevent.x
+ self.mouse_y = evt.mouseevent.y
+ self.got_artist = True
+ if self._use_blit:
+ self.ref_artist.set_animated(True)
+ self.canvas.draw()
+ self.background = \
+ self.canvas.copy_from_bbox(self.ref_artist.figure.bbox)
+ self.ref_artist.draw(
+ self.ref_artist.figure._get_renderer())
+ self.canvas.blit()
+ self.save_offset()
+
+ def on_release(self, event):
+ if self._check_still_parented() and self.got_artist:
+ self.finalize_offset()
+ self.got_artist = False
+ if self._use_blit:
+ self.ref_artist.set_animated(False)
+
+ def _check_still_parented(self):
+ if self.ref_artist.figure is None:
+ self.disconnect()
+ return False
+ else:
+ return True
+
+ def disconnect(self):
+ """Disconnect the callbacks."""
+ for disconnector in self._disconnectors:
+ disconnector()
+
+ def save_offset(self):
+ pass
+
+ def update_offset(self, dx, dy):
+ pass
+
+ def finalize_offset(self):
+ pass
+
+
+class DraggableOffsetBox(DraggableBase):
+ def __init__(self, ref_artist, offsetbox, use_blit=False):
+ super().__init__(ref_artist, use_blit=use_blit)
+ self.offsetbox = offsetbox
+
+ def save_offset(self):
+ offsetbox = self.offsetbox
+ renderer = offsetbox.figure._get_renderer()
+ offset = offsetbox.get_offset(offsetbox.get_bbox(renderer), renderer)
+ self.offsetbox_x, self.offsetbox_y = offset
+ self.offsetbox.set_offset(offset)
+
+ def update_offset(self, dx, dy):
+ loc_in_canvas = self.offsetbox_x + dx, self.offsetbox_y + dy
+ self.offsetbox.set_offset(loc_in_canvas)
+
+ def get_loc_in_canvas(self):
+ offsetbox = self.offsetbox
+ renderer = offsetbox.figure._get_renderer()
+ bbox = offsetbox.get_bbox(renderer)
+ ox, oy = offsetbox._offset
+ loc_in_canvas = (ox + bbox.x0, oy + bbox.y0)
+ return loc_in_canvas
+
+
+class DraggableAnnotation(DraggableBase):
+ def __init__(self, annotation, use_blit=False):
+ super().__init__(annotation, use_blit=use_blit)
+ self.annotation = annotation
+
+ def save_offset(self):
+ ann = self.annotation
+ self.ox, self.oy = ann.get_transform().transform(ann.xyann)
+
+ def update_offset(self, dx, dy):
+ ann = self.annotation
+ ann.xyann = ann.get_transform().inverted().transform(
+ (self.ox + dx, self.oy + dy))
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/patches.py b/omnilmm/lib/python3.10/site-packages/matplotlib/patches.py
new file mode 100644
index 0000000000000000000000000000000000000000..98e96e3731364255931673e95f7d117989f1923f
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/patches.py
@@ -0,0 +1,4614 @@
+r"""
+Patches are `.Artist`\s with a face color and an edge color.
+"""
+
+import functools
+import inspect
+import math
+from numbers import Number
+import textwrap
+from types import SimpleNamespace
+from collections import namedtuple
+from matplotlib.transforms import Affine2D
+
+import numpy as np
+
+import matplotlib as mpl
+from . import (_api, artist, cbook, colors, _docstring, hatch as mhatch,
+ lines as mlines, transforms)
+from .bezier import (
+ NonIntersectingPathException, get_cos_sin, get_intersection,
+ get_parallels, inside_circle, make_wedged_bezier2,
+ split_bezier_intersecting_with_closedpath, split_path_inout)
+from .path import Path
+from ._enums import JoinStyle, CapStyle
+
+
+@_docstring.interpd
+@_api.define_aliases({
+ "antialiased": ["aa"],
+ "edgecolor": ["ec"],
+ "facecolor": ["fc"],
+ "linestyle": ["ls"],
+ "linewidth": ["lw"],
+})
+class Patch(artist.Artist):
+ """
+ A patch is a 2D artist with a face color and an edge color.
+
+ If any of *edgecolor*, *facecolor*, *linewidth*, or *antialiased*
+ are *None*, they default to their rc params setting.
+ """
+ zorder = 1
+
+ # Whether to draw an edge by default. Set on a
+ # subclass-by-subclass basis.
+ _edge_default = False
+
+ @_api.make_keyword_only("3.6", name="edgecolor")
+ def __init__(self,
+ edgecolor=None,
+ facecolor=None,
+ color=None,
+ linewidth=None,
+ linestyle=None,
+ antialiased=None,
+ hatch=None,
+ fill=True,
+ capstyle=None,
+ joinstyle=None,
+ **kwargs):
+ """
+ The following kwarg properties are supported
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__()
+
+ if linestyle is None:
+ linestyle = "solid"
+ if capstyle is None:
+ capstyle = CapStyle.butt
+ if joinstyle is None:
+ joinstyle = JoinStyle.miter
+
+ self._hatch_color = colors.to_rgba(mpl.rcParams['hatch.color'])
+ self._fill = True # needed for set_facecolor call
+ if color is not None:
+ if edgecolor is not None or facecolor is not None:
+ _api.warn_external(
+ "Setting the 'color' property will override "
+ "the edgecolor or facecolor properties.")
+ self.set_color(color)
+ else:
+ self.set_edgecolor(edgecolor)
+ self.set_facecolor(facecolor)
+
+ self._linewidth = 0
+ self._unscaled_dash_pattern = (0, None) # offset, dash
+ self._dash_pattern = (0, None) # offset, dash (scaled by linewidth)
+
+ self.set_fill(fill)
+ self.set_linestyle(linestyle)
+ self.set_linewidth(linewidth)
+ self.set_antialiased(antialiased)
+ self.set_hatch(hatch)
+ self.set_capstyle(capstyle)
+ self.set_joinstyle(joinstyle)
+
+ if len(kwargs):
+ self._internal_update(kwargs)
+
+ def get_verts(self):
+ """
+ Return a copy of the vertices used in this patch.
+
+ If the patch contains Bézier curves, the curves will be interpolated by
+ line segments. To access the curves as curves, use `get_path`.
+ """
+ trans = self.get_transform()
+ path = self.get_path()
+ polygons = path.to_polygons(trans)
+ if len(polygons):
+ return polygons[0]
+ return []
+
+ def _process_radius(self, radius):
+ if radius is not None:
+ return radius
+ if isinstance(self._picker, Number):
+ _radius = self._picker
+ else:
+ if self.get_edgecolor()[3] == 0:
+ _radius = 0
+ else:
+ _radius = self.get_linewidth()
+ return _radius
+
+ def contains(self, mouseevent, radius=None):
+ """
+ Test whether the mouse event occurred in the patch.
+
+ Returns
+ -------
+ (bool, empty dict)
+ """
+ inside, info = self._default_contains(mouseevent)
+ if inside is not None:
+ return inside, info
+ radius = self._process_radius(radius)
+ codes = self.get_path().codes
+ if codes is not None:
+ vertices = self.get_path().vertices
+ # if the current path is concatenated by multiple sub paths.
+ # get the indexes of the starting code(MOVETO) of all sub paths
+ idxs, = np.where(codes == Path.MOVETO)
+ # Don't split before the first MOVETO.
+ idxs = idxs[1:]
+ subpaths = map(
+ Path, np.split(vertices, idxs), np.split(codes, idxs))
+ else:
+ subpaths = [self.get_path()]
+ inside = any(
+ subpath.contains_point(
+ (mouseevent.x, mouseevent.y), self.get_transform(), radius)
+ for subpath in subpaths)
+ return inside, {}
+
+ def contains_point(self, point, radius=None):
+ """
+ Return whether the given point is inside the patch.
+
+ Parameters
+ ----------
+ point : (float, float)
+ The point (x, y) to check, in target coordinates of
+ ``self.get_transform()``. These are display coordinates for patches
+ that are added to a figure or axes.
+ radius : float, optional
+ Additional margin on the patch in target coordinates of
+ ``self.get_transform()``. See `.Path.contains_point` for further
+ details.
+
+ Returns
+ -------
+ bool
+
+ Notes
+ -----
+ The proper use of this method depends on the transform of the patch.
+ Isolated patches do not have a transform. In this case, the patch
+ creation coordinates and the point coordinates match. The following
+ example checks that the center of a circle is within the circle
+
+ >>> center = 0, 0
+ >>> c = Circle(center, radius=1)
+ >>> c.contains_point(center)
+ True
+
+ The convention of checking against the transformed patch stems from
+ the fact that this method is predominantly used to check if display
+ coordinates (e.g. from mouse events) are within the patch. If you want
+ to do the above check with data coordinates, you have to properly
+ transform them first:
+
+ >>> center = 0, 0
+ >>> c = Circle(center, radius=1)
+ >>> plt.gca().add_patch(c)
+ >>> transformed_center = c.get_transform().transform(center)
+ >>> c.contains_point(transformed_center)
+ True
+
+ """
+ radius = self._process_radius(radius)
+ return self.get_path().contains_point(point,
+ self.get_transform(),
+ radius)
+
+ def contains_points(self, points, radius=None):
+ """
+ Return whether the given points are inside the patch.
+
+ Parameters
+ ----------
+ points : (N, 2) array
+ The points to check, in target coordinates of
+ ``self.get_transform()``. These are display coordinates for patches
+ that are added to a figure or axes. Columns contain x and y values.
+ radius : float, optional
+ Additional margin on the patch in target coordinates of
+ ``self.get_transform()``. See `.Path.contains_point` for further
+ details.
+
+ Returns
+ -------
+ length-N bool array
+
+ Notes
+ -----
+ The proper use of this method depends on the transform of the patch.
+ See the notes on `.Patch.contains_point`.
+ """
+ radius = self._process_radius(radius)
+ return self.get_path().contains_points(points,
+ self.get_transform(),
+ radius)
+
+ def update_from(self, other):
+ # docstring inherited.
+ super().update_from(other)
+ # For some properties we don't need or don't want to go through the
+ # getters/setters, so we just copy them directly.
+ self._edgecolor = other._edgecolor
+ self._facecolor = other._facecolor
+ self._original_edgecolor = other._original_edgecolor
+ self._original_facecolor = other._original_facecolor
+ self._fill = other._fill
+ self._hatch = other._hatch
+ self._hatch_color = other._hatch_color
+ self._unscaled_dash_pattern = other._unscaled_dash_pattern
+ self.set_linewidth(other._linewidth) # also sets scaled dashes
+ self.set_transform(other.get_data_transform())
+ # If the transform of other needs further initialization, then it will
+ # be the case for this artist too.
+ self._transformSet = other.is_transform_set()
+
+ def get_extents(self):
+ """
+ Return the `Patch`'s axis-aligned extents as a `~.transforms.Bbox`.
+ """
+ return self.get_path().get_extents(self.get_transform())
+
+ def get_transform(self):
+ """Return the `~.transforms.Transform` applied to the `Patch`."""
+ return self.get_patch_transform() + artist.Artist.get_transform(self)
+
+ def get_data_transform(self):
+ """
+ Return the `~.transforms.Transform` mapping data coordinates to
+ physical coordinates.
+ """
+ return artist.Artist.get_transform(self)
+
+ def get_patch_transform(self):
+ """
+ Return the `~.transforms.Transform` instance mapping patch coordinates
+ to data coordinates.
+
+ For example, one may define a patch of a circle which represents a
+ radius of 5 by providing coordinates for a unit circle, and a
+ transform which scales the coordinates (the patch coordinate) by 5.
+ """
+ return transforms.IdentityTransform()
+
+ def get_antialiased(self):
+ """Return whether antialiasing is used for drawing."""
+ return self._antialiased
+
+ def get_edgecolor(self):
+ """Return the edge color."""
+ return self._edgecolor
+
+ def get_facecolor(self):
+ """Return the face color."""
+ return self._facecolor
+
+ def get_linewidth(self):
+ """Return the line width in points."""
+ return self._linewidth
+
+ def get_linestyle(self):
+ """Return the linestyle."""
+ return self._linestyle
+
+ def set_antialiased(self, aa):
+ """
+ Set whether to use antialiased rendering.
+
+ Parameters
+ ----------
+ aa : bool or None
+ """
+ if aa is None:
+ aa = mpl.rcParams['patch.antialiased']
+ self._antialiased = aa
+ self.stale = True
+
+ def _set_edgecolor(self, color):
+ set_hatch_color = True
+ if color is None:
+ if (mpl.rcParams['patch.force_edgecolor'] or
+ not self._fill or self._edge_default):
+ color = mpl.rcParams['patch.edgecolor']
+ else:
+ color = 'none'
+ set_hatch_color = False
+
+ self._edgecolor = colors.to_rgba(color, self._alpha)
+ if set_hatch_color:
+ self._hatch_color = self._edgecolor
+ self.stale = True
+
+ def set_edgecolor(self, color):
+ """
+ Set the patch edge color.
+
+ Parameters
+ ----------
+ color : color or None
+ """
+ self._original_edgecolor = color
+ self._set_edgecolor(color)
+
+ def _set_facecolor(self, color):
+ if color is None:
+ color = mpl.rcParams['patch.facecolor']
+ alpha = self._alpha if self._fill else 0
+ self._facecolor = colors.to_rgba(color, alpha)
+ self.stale = True
+
+ def set_facecolor(self, color):
+ """
+ Set the patch face color.
+
+ Parameters
+ ----------
+ color : color or None
+ """
+ self._original_facecolor = color
+ self._set_facecolor(color)
+
+ def set_color(self, c):
+ """
+ Set both the edgecolor and the facecolor.
+
+ Parameters
+ ----------
+ c : color
+
+ See Also
+ --------
+ Patch.set_facecolor, Patch.set_edgecolor
+ For setting the edge or face color individually.
+ """
+ self.set_facecolor(c)
+ self.set_edgecolor(c)
+
+ def set_alpha(self, alpha):
+ # docstring inherited
+ super().set_alpha(alpha)
+ self._set_facecolor(self._original_facecolor)
+ self._set_edgecolor(self._original_edgecolor)
+ # stale is already True
+
+ def set_linewidth(self, w):
+ """
+ Set the patch linewidth in points.
+
+ Parameters
+ ----------
+ w : float or None
+ """
+ if w is None:
+ w = mpl.rcParams['patch.linewidth']
+ self._linewidth = float(w)
+ self._dash_pattern = mlines._scale_dashes(
+ *self._unscaled_dash_pattern, w)
+ self.stale = True
+
+ def set_linestyle(self, ls):
+ """
+ Set the patch linestyle.
+
+ ========================================== =================
+ linestyle description
+ ========================================== =================
+ ``'-'`` or ``'solid'`` solid line
+ ``'--'`` or ``'dashed'`` dashed line
+ ``'-.'`` or ``'dashdot'`` dash-dotted line
+ ``':'`` or ``'dotted'`` dotted line
+ ``'none'``, ``'None'``, ``' '``, or ``''`` draw nothing
+ ========================================== =================
+
+ Alternatively a dash tuple of the following form can be provided::
+
+ (offset, onoffseq)
+
+ where ``onoffseq`` is an even length tuple of on and off ink in points.
+
+ Parameters
+ ----------
+ ls : {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
+ The line style.
+ """
+ if ls is None:
+ ls = "solid"
+ if ls in [' ', '', 'none']:
+ ls = 'None'
+ self._linestyle = ls
+ self._unscaled_dash_pattern = mlines._get_dash_pattern(ls)
+ self._dash_pattern = mlines._scale_dashes(
+ *self._unscaled_dash_pattern, self._linewidth)
+ self.stale = True
+
+ def set_fill(self, b):
+ """
+ Set whether to fill the patch.
+
+ Parameters
+ ----------
+ b : bool
+ """
+ self._fill = bool(b)
+ self._set_facecolor(self._original_facecolor)
+ self._set_edgecolor(self._original_edgecolor)
+ self.stale = True
+
+ def get_fill(self):
+ """Return whether the patch is filled."""
+ return self._fill
+
+ # Make fill a property so as to preserve the long-standing
+ # but somewhat inconsistent behavior in which fill was an
+ # attribute.
+ fill = property(get_fill, set_fill)
+
+ @_docstring.interpd
+ def set_capstyle(self, s):
+ """
+ Set the `.CapStyle`.
+
+ The default capstyle is 'round' for `.FancyArrowPatch` and 'butt' for
+ all other patches.
+
+ Parameters
+ ----------
+ s : `.CapStyle` or %(CapStyle)s
+ """
+ cs = CapStyle(s)
+ self._capstyle = cs
+ self.stale = True
+
+ def get_capstyle(self):
+ """Return the capstyle."""
+ return self._capstyle.name
+
+ @_docstring.interpd
+ def set_joinstyle(self, s):
+ """
+ Set the `.JoinStyle`.
+
+ The default joinstyle is 'round' for `.FancyArrowPatch` and 'miter' for
+ all other patches.
+
+ Parameters
+ ----------
+ s : `.JoinStyle` or %(JoinStyle)s
+ """
+ js = JoinStyle(s)
+ self._joinstyle = js
+ self.stale = True
+
+ def get_joinstyle(self):
+ """Return the joinstyle."""
+ return self._joinstyle.name
+
+ def set_hatch(self, hatch):
+ r"""
+ Set the hatching pattern.
+
+ *hatch* can be one of::
+
+ / - diagonal hatching
+ \ - back diagonal
+ | - vertical
+ - - horizontal
+ + - crossed
+ x - crossed diagonal
+ o - small circle
+ O - large circle
+ . - dots
+ * - stars
+
+ Letters can be combined, in which case all the specified
+ hatchings are done. If same letter repeats, it increases the
+ density of hatching of that pattern.
+
+ Hatching is supported in the PostScript, PDF, SVG and Agg
+ backends only.
+
+ Parameters
+ ----------
+ hatch : {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
+ """
+ # Use validate_hatch(list) after deprecation.
+ mhatch._validate_hatch_pattern(hatch)
+ self._hatch = hatch
+ self.stale = True
+
+ def get_hatch(self):
+ """Return the hatching pattern."""
+ return self._hatch
+
+ def _draw_paths_with_artist_properties(
+ self, renderer, draw_path_args_list):
+ """
+ ``draw()`` helper factored out for sharing with `FancyArrowPatch`.
+
+ Configure *renderer* and the associated graphics context *gc*
+ from the artist properties, then repeatedly call
+ ``renderer.draw_path(gc, *draw_path_args)`` for each tuple
+ *draw_path_args* in *draw_path_args_list*.
+ """
+
+ renderer.open_group('patch', self.get_gid())
+ gc = renderer.new_gc()
+
+ gc.set_foreground(self._edgecolor, isRGBA=True)
+
+ lw = self._linewidth
+ if self._edgecolor[3] == 0 or self._linestyle == 'None':
+ lw = 0
+ gc.set_linewidth(lw)
+ gc.set_dashes(*self._dash_pattern)
+ gc.set_capstyle(self._capstyle)
+ gc.set_joinstyle(self._joinstyle)
+
+ gc.set_antialiased(self._antialiased)
+ self._set_gc_clip(gc)
+ gc.set_url(self._url)
+ gc.set_snap(self.get_snap())
+
+ gc.set_alpha(self._alpha)
+
+ if self._hatch:
+ gc.set_hatch(self._hatch)
+ gc.set_hatch_color(self._hatch_color)
+
+ if self.get_sketch_params() is not None:
+ gc.set_sketch_params(*self.get_sketch_params())
+
+ if self.get_path_effects():
+ from matplotlib.patheffects import PathEffectRenderer
+ renderer = PathEffectRenderer(self.get_path_effects(), renderer)
+
+ for draw_path_args in draw_path_args_list:
+ renderer.draw_path(gc, *draw_path_args)
+
+ gc.restore()
+ renderer.close_group('patch')
+ self.stale = False
+
+ @artist.allow_rasterization
+ def draw(self, renderer):
+ # docstring inherited
+ if not self.get_visible():
+ return
+ path = self.get_path()
+ transform = self.get_transform()
+ tpath = transform.transform_path_non_affine(path)
+ affine = transform.get_affine()
+ self._draw_paths_with_artist_properties(
+ renderer,
+ [(tpath, affine,
+ # Work around a bug in the PDF and SVG renderers, which
+ # do not draw the hatches if the facecolor is fully
+ # transparent, but do if it is None.
+ self._facecolor if self._facecolor[3] else None)])
+
+ def get_path(self):
+ """Return the path of this patch."""
+ raise NotImplementedError('Derived must override')
+
+ def get_window_extent(self, renderer=None):
+ return self.get_path().get_extents(self.get_transform())
+
+ def _convert_xy_units(self, xy):
+ """Convert x and y units for a tuple (x, y)."""
+ x = self.convert_xunits(xy[0])
+ y = self.convert_yunits(xy[1])
+ return x, y
+
+
+class Shadow(Patch):
+ def __str__(self):
+ return f"Shadow({self.patch})"
+
+ @_docstring.dedent_interpd
+ def __init__(self, patch, ox, oy, **kwargs):
+ """
+ Create a shadow of the given *patch*.
+
+ By default, the shadow will have the same face color as the *patch*,
+ but darkened.
+
+ Parameters
+ ----------
+ patch : `~matplotlib.patches.Patch`
+ The patch to create the shadow for.
+ ox, oy : float
+ The shift of the shadow in data coordinates, scaled by a factor
+ of dpi/72.
+ **kwargs
+ Properties of the shadow patch. Supported keys are:
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__()
+ self.patch = patch
+ self._ox, self._oy = ox, oy
+ self._shadow_transform = transforms.Affine2D()
+
+ self.update_from(self.patch)
+ color = .3 * np.asarray(colors.to_rgb(self.patch.get_facecolor()))
+ self.update({'facecolor': color, 'edgecolor': color, 'alpha': 0.5,
+ # Place shadow patch directly behind the inherited patch.
+ 'zorder': np.nextafter(self.patch.zorder, -np.inf),
+ **kwargs})
+
+ def _update_transform(self, renderer):
+ ox = renderer.points_to_pixels(self._ox)
+ oy = renderer.points_to_pixels(self._oy)
+ self._shadow_transform.clear().translate(ox, oy)
+
+ def get_path(self):
+ return self.patch.get_path()
+
+ def get_patch_transform(self):
+ return self.patch.get_patch_transform() + self._shadow_transform
+
+ def draw(self, renderer):
+ self._update_transform(renderer)
+ super().draw(renderer)
+
+
+class Rectangle(Patch):
+ """
+ A rectangle defined via an anchor point *xy* and its *width* and *height*.
+
+ The rectangle extends from ``xy[0]`` to ``xy[0] + width`` in x-direction
+ and from ``xy[1]`` to ``xy[1] + height`` in y-direction. ::
+
+ : +------------------+
+ : | |
+ : height |
+ : | |
+ : (xy)---- width -----+
+
+ One may picture *xy* as the bottom left corner, but which corner *xy* is
+ actually depends on the direction of the axis and the sign of *width*
+ and *height*; e.g. *xy* would be the bottom right corner if the x-axis
+ was inverted or if *width* was negative.
+ """
+
+ def __str__(self):
+ pars = self._x0, self._y0, self._width, self._height, self.angle
+ fmt = "Rectangle(xy=(%g, %g), width=%g, height=%g, angle=%g)"
+ return fmt % pars
+
+ @_docstring.dedent_interpd
+ @_api.make_keyword_only("3.6", name="angle")
+ def __init__(self, xy, width, height, angle=0.0, *,
+ rotation_point='xy', **kwargs):
+ """
+ Parameters
+ ----------
+ xy : (float, float)
+ The anchor point.
+ width : float
+ Rectangle width.
+ height : float
+ Rectangle height.
+ angle : float, default: 0
+ Rotation in degrees anti-clockwise about the rotation point.
+ rotation_point : {'xy', 'center', (number, number)}, default: 'xy'
+ If ``'xy'``, rotate around the anchor point. If ``'center'`` rotate
+ around the center. If 2-tuple of number, rotate around this
+ coordinate.
+
+ Other Parameters
+ ----------------
+ **kwargs : `~matplotlib.patches.Patch` properties
+ %(Patch:kwdoc)s
+ """
+ super().__init__(**kwargs)
+ self._x0 = xy[0]
+ self._y0 = xy[1]
+ self._width = width
+ self._height = height
+ self.angle = float(angle)
+ self.rotation_point = rotation_point
+ # Required for RectangleSelector with axes aspect ratio != 1
+ # The patch is defined in data coordinates and when changing the
+ # selector with square modifier and not in data coordinates, we need
+ # to correct for the aspect ratio difference between the data and
+ # display coordinate systems. Its value is typically provide by
+ # Axes._get_aspect_ratio()
+ self._aspect_ratio_correction = 1.0
+ self._convert_units() # Validate the inputs.
+
+ def get_path(self):
+ """Return the vertices of the rectangle."""
+ return Path.unit_rectangle()
+
+ def _convert_units(self):
+ """Convert bounds of the rectangle."""
+ x0 = self.convert_xunits(self._x0)
+ y0 = self.convert_yunits(self._y0)
+ x1 = self.convert_xunits(self._x0 + self._width)
+ y1 = self.convert_yunits(self._y0 + self._height)
+ return x0, y0, x1, y1
+
+ def get_patch_transform(self):
+ # Note: This cannot be called until after this has been added to
+ # an Axes, otherwise unit conversion will fail. This makes it very
+ # important to call the accessor method and not directly access the
+ # transformation member variable.
+ bbox = self.get_bbox()
+ if self.rotation_point == 'center':
+ width, height = bbox.x1 - bbox.x0, bbox.y1 - bbox.y0
+ rotation_point = bbox.x0 + width / 2., bbox.y0 + height / 2.
+ elif self.rotation_point == 'xy':
+ rotation_point = bbox.x0, bbox.y0
+ else:
+ rotation_point = self.rotation_point
+ return transforms.BboxTransformTo(bbox) \
+ + transforms.Affine2D() \
+ .translate(-rotation_point[0], -rotation_point[1]) \
+ .scale(1, self._aspect_ratio_correction) \
+ .rotate_deg(self.angle) \
+ .scale(1, 1 / self._aspect_ratio_correction) \
+ .translate(*rotation_point)
+
+ @property
+ def rotation_point(self):
+ """The rotation point of the patch."""
+ return self._rotation_point
+
+ @rotation_point.setter
+ def rotation_point(self, value):
+ if value in ['center', 'xy'] or (
+ isinstance(value, tuple) and len(value) == 2 and
+ isinstance(value[0], Number) and isinstance(value[1], Number)
+ ):
+ self._rotation_point = value
+ else:
+ raise ValueError("`rotation_point` must be one of "
+ "{'xy', 'center', (number, number)}.")
+
+ def get_x(self):
+ """Return the left coordinate of the rectangle."""
+ return self._x0
+
+ def get_y(self):
+ """Return the bottom coordinate of the rectangle."""
+ return self._y0
+
+ def get_xy(self):
+ """Return the left and bottom coords of the rectangle as a tuple."""
+ return self._x0, self._y0
+
+ def get_corners(self):
+ """
+ Return the corners of the rectangle, moving anti-clockwise from
+ (x0, y0).
+ """
+ return self.get_patch_transform().transform(
+ [(0, 0), (1, 0), (1, 1), (0, 1)])
+
+ def get_center(self):
+ """Return the centre of the rectangle."""
+ return self.get_patch_transform().transform((0.5, 0.5))
+
+ def get_width(self):
+ """Return the width of the rectangle."""
+ return self._width
+
+ def get_height(self):
+ """Return the height of the rectangle."""
+ return self._height
+
+ def get_angle(self):
+ """Get the rotation angle in degrees."""
+ return self.angle
+
+ def set_x(self, x):
+ """Set the left coordinate of the rectangle."""
+ self._x0 = x
+ self.stale = True
+
+ def set_y(self, y):
+ """Set the bottom coordinate of the rectangle."""
+ self._y0 = y
+ self.stale = True
+
+ def set_angle(self, angle):
+ """
+ Set the rotation angle in degrees.
+
+ The rotation is performed anti-clockwise around *xy*.
+ """
+ self.angle = angle
+ self.stale = True
+
+ def set_xy(self, xy):
+ """
+ Set the left and bottom coordinates of the rectangle.
+
+ Parameters
+ ----------
+ xy : (float, float)
+ """
+ self._x0, self._y0 = xy
+ self.stale = True
+
+ def set_width(self, w):
+ """Set the width of the rectangle."""
+ self._width = w
+ self.stale = True
+
+ def set_height(self, h):
+ """Set the height of the rectangle."""
+ self._height = h
+ self.stale = True
+
+ def set_bounds(self, *args):
+ """
+ Set the bounds of the rectangle as *left*, *bottom*, *width*, *height*.
+
+ The values may be passed as separate parameters or as a tuple::
+
+ set_bounds(left, bottom, width, height)
+ set_bounds((left, bottom, width, height))
+
+ .. ACCEPTS: (left, bottom, width, height)
+ """
+ if len(args) == 1:
+ l, b, w, h = args[0]
+ else:
+ l, b, w, h = args
+ self._x0 = l
+ self._y0 = b
+ self._width = w
+ self._height = h
+ self.stale = True
+
+ def get_bbox(self):
+ """Return the `.Bbox`."""
+ x0, y0, x1, y1 = self._convert_units()
+ return transforms.Bbox.from_extents(x0, y0, x1, y1)
+
+ xy = property(get_xy, set_xy)
+
+
+class RegularPolygon(Patch):
+ """A regular polygon patch."""
+
+ def __str__(self):
+ s = "RegularPolygon((%g, %g), %d, radius=%g, orientation=%g)"
+ return s % (self.xy[0], self.xy[1], self.numvertices, self.radius,
+ self.orientation)
+
+ @_docstring.dedent_interpd
+ @_api.make_keyword_only("3.6", name="radius")
+ def __init__(self, xy, numVertices, radius=5, orientation=0,
+ **kwargs):
+ """
+ Parameters
+ ----------
+ xy : (float, float)
+ The center position.
+
+ numVertices : int
+ The number of vertices.
+
+ radius : float
+ The distance from the center to each of the vertices.
+
+ orientation : float
+ The polygon rotation angle (in radians).
+
+ **kwargs
+ `Patch` properties:
+
+ %(Patch:kwdoc)s
+ """
+ self.xy = xy
+ self.numvertices = numVertices
+ self.orientation = orientation
+ self.radius = radius
+ self._path = Path.unit_regular_polygon(numVertices)
+ self._patch_transform = transforms.Affine2D()
+ super().__init__(**kwargs)
+
+ def get_path(self):
+ return self._path
+
+ def get_patch_transform(self):
+ return self._patch_transform.clear() \
+ .scale(self.radius) \
+ .rotate(self.orientation) \
+ .translate(*self.xy)
+
+
+class PathPatch(Patch):
+ """A general polycurve path patch."""
+
+ _edge_default = True
+
+ def __str__(self):
+ s = "PathPatch%d((%g, %g) ...)"
+ return s % (len(self._path.vertices), *tuple(self._path.vertices[0]))
+
+ @_docstring.dedent_interpd
+ def __init__(self, path, **kwargs):
+ """
+ *path* is a `.Path` object.
+
+ Valid keyword arguments are:
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__(**kwargs)
+ self._path = path
+
+ def get_path(self):
+ return self._path
+
+ def set_path(self, path):
+ self._path = path
+
+
+class StepPatch(PathPatch):
+ """
+ A path patch describing a stepwise constant function.
+
+ By default, the path is not closed and starts and stops at
+ baseline value.
+ """
+
+ _edge_default = False
+
+ @_docstring.dedent_interpd
+ def __init__(self, values, edges, *,
+ orientation='vertical', baseline=0, **kwargs):
+ """
+ Parameters
+ ----------
+ values : array-like
+ The step heights.
+
+ edges : array-like
+ The edge positions, with ``len(edges) == len(vals) + 1``,
+ between which the curve takes on vals values.
+
+ orientation : {'vertical', 'horizontal'}, default: 'vertical'
+ The direction of the steps. Vertical means that *values* are
+ along the y-axis, and edges are along the x-axis.
+
+ baseline : float, array-like or None, default: 0
+ The bottom value of the bounding edges or when
+ ``fill=True``, position of lower edge. If *fill* is
+ True or an array is passed to *baseline*, a closed
+ path is drawn.
+
+ Other valid keyword arguments are:
+
+ %(Patch:kwdoc)s
+ """
+ self.orientation = orientation
+ self._edges = np.asarray(edges)
+ self._values = np.asarray(values)
+ self._baseline = np.asarray(baseline) if baseline is not None else None
+ self._update_path()
+ super().__init__(self._path, **kwargs)
+
+ def _update_path(self):
+ if np.isnan(np.sum(self._edges)):
+ raise ValueError('Nan values in "edges" are disallowed')
+ if self._edges.size - 1 != self._values.size:
+ raise ValueError('Size mismatch between "values" and "edges". '
+ "Expected `len(values) + 1 == len(edges)`, but "
+ f"`len(values) = {self._values.size}` and "
+ f"`len(edges) = {self._edges.size}`.")
+ # Initializing with empty arrays allows supporting empty stairs.
+ verts, codes = [np.empty((0, 2))], [np.empty(0, dtype=Path.code_type)]
+
+ _nan_mask = np.isnan(self._values)
+ if self._baseline is not None:
+ _nan_mask |= np.isnan(self._baseline)
+ for idx0, idx1 in cbook.contiguous_regions(~_nan_mask):
+ x = np.repeat(self._edges[idx0:idx1+1], 2)
+ y = np.repeat(self._values[idx0:idx1], 2)
+ if self._baseline is None:
+ y = np.concatenate([y[:1], y, y[-1:]])
+ elif self._baseline.ndim == 0: # single baseline value
+ y = np.concatenate([[self._baseline], y, [self._baseline]])
+ elif self._baseline.ndim == 1: # baseline array
+ base = np.repeat(self._baseline[idx0:idx1], 2)[::-1]
+ x = np.concatenate([x, x[::-1]])
+ y = np.concatenate([base[-1:], y, base[:1],
+ base[:1], base, base[-1:]])
+ else: # no baseline
+ raise ValueError('Invalid `baseline` specified')
+ if self.orientation == 'vertical':
+ xy = np.column_stack([x, y])
+ else:
+ xy = np.column_stack([y, x])
+ verts.append(xy)
+ codes.append([Path.MOVETO] + [Path.LINETO]*(len(xy)-1))
+ self._path = Path(np.concatenate(verts), np.concatenate(codes))
+
+ def get_data(self):
+ """Get `.StepPatch` values, edges and baseline as namedtuple."""
+ StairData = namedtuple('StairData', 'values edges baseline')
+ return StairData(self._values, self._edges, self._baseline)
+
+ def set_data(self, values=None, edges=None, baseline=None):
+ """
+ Set `.StepPatch` values, edges and baseline.
+
+ Parameters
+ ----------
+ values : 1D array-like or None
+ Will not update values, if passing None
+ edges : 1D array-like, optional
+ baseline : float, 1D array-like or None
+ """
+ if values is None and edges is None and baseline is None:
+ raise ValueError("Must set *values*, *edges* or *baseline*.")
+ if values is not None:
+ self._values = np.asarray(values)
+ if edges is not None:
+ self._edges = np.asarray(edges)
+ if baseline is not None:
+ self._baseline = np.asarray(baseline)
+ self._update_path()
+ self.stale = True
+
+
+class Polygon(Patch):
+ """A general polygon patch."""
+
+ def __str__(self):
+ if len(self._path.vertices):
+ s = "Polygon%d((%g, %g) ...)"
+ return s % (len(self._path.vertices), *self._path.vertices[0])
+ else:
+ return "Polygon0()"
+
+ @_docstring.dedent_interpd
+ @_api.make_keyword_only("3.6", name="closed")
+ def __init__(self, xy, closed=True, **kwargs):
+ """
+ *xy* is a numpy array with shape Nx2.
+
+ If *closed* is *True*, the polygon will be closed so the
+ starting and ending points are the same.
+
+ Valid keyword arguments are:
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__(**kwargs)
+ self._closed = closed
+ self.set_xy(xy)
+
+ def get_path(self):
+ """Get the `.Path` of the polygon."""
+ return self._path
+
+ def get_closed(self):
+ """Return whether the polygon is closed."""
+ return self._closed
+
+ def set_closed(self, closed):
+ """
+ Set whether the polygon is closed.
+
+ Parameters
+ ----------
+ closed : bool
+ True if the polygon is closed
+ """
+ if self._closed == bool(closed):
+ return
+ self._closed = bool(closed)
+ self.set_xy(self.get_xy())
+ self.stale = True
+
+ def get_xy(self):
+ """
+ Get the vertices of the path.
+
+ Returns
+ -------
+ (N, 2) numpy array
+ The coordinates of the vertices.
+ """
+ return self._path.vertices
+
+ def set_xy(self, xy):
+ """
+ Set the vertices of the polygon.
+
+ Parameters
+ ----------
+ xy : (N, 2) array-like
+ The coordinates of the vertices.
+
+ Notes
+ -----
+ Unlike `.Path`, we do not ignore the last input vertex. If the
+ polygon is meant to be closed, and the last point of the polygon is not
+ equal to the first, we assume that the user has not explicitly passed a
+ ``CLOSEPOLY`` vertex, and add it ourselves.
+ """
+ xy = np.asarray(xy)
+ nverts, _ = xy.shape
+ if self._closed:
+ # if the first and last vertex are the "same", then we assume that
+ # the user explicitly passed the CLOSEPOLY vertex. Otherwise, we
+ # have to append one since the last vertex will be "ignored" by
+ # Path
+ if nverts == 1 or nverts > 1 and (xy[0] != xy[-1]).any():
+ xy = np.concatenate([xy, [xy[0]]])
+ else:
+ # if we aren't closed, and the last vertex matches the first, then
+ # we assume we have an unnecessary CLOSEPOLY vertex and remove it
+ if nverts > 2 and (xy[0] == xy[-1]).all():
+ xy = xy[:-1]
+ self._path = Path(xy, closed=self._closed)
+ self.stale = True
+
+ xy = property(get_xy, set_xy,
+ doc='The vertices of the path as (N, 2) numpy array.')
+
+
+class Wedge(Patch):
+ """Wedge shaped patch."""
+
+ def __str__(self):
+ pars = (self.center[0], self.center[1], self.r,
+ self.theta1, self.theta2, self.width)
+ fmt = "Wedge(center=(%g, %g), r=%g, theta1=%g, theta2=%g, width=%s)"
+ return fmt % pars
+
+ @_docstring.dedent_interpd
+ @_api.make_keyword_only("3.6", name="width")
+ def __init__(self, center, r, theta1, theta2, width=None, **kwargs):
+ """
+ A wedge centered at *x*, *y* center with radius *r* that
+ sweeps *theta1* to *theta2* (in degrees). If *width* is given,
+ then a partial wedge is drawn from inner radius *r* - *width*
+ to outer radius *r*.
+
+ Valid keyword arguments are:
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__(**kwargs)
+ self.center = center
+ self.r, self.width = r, width
+ self.theta1, self.theta2 = theta1, theta2
+ self._patch_transform = transforms.IdentityTransform()
+ self._recompute_path()
+
+ def _recompute_path(self):
+ # Inner and outer rings are connected unless the annulus is complete
+ if abs((self.theta2 - self.theta1) - 360) <= 1e-12:
+ theta1, theta2 = 0, 360
+ connector = Path.MOVETO
+ else:
+ theta1, theta2 = self.theta1, self.theta2
+ connector = Path.LINETO
+
+ # Form the outer ring
+ arc = Path.arc(theta1, theta2)
+
+ if self.width is not None:
+ # Partial annulus needs to draw the outer ring
+ # followed by a reversed and scaled inner ring
+ v1 = arc.vertices
+ v2 = arc.vertices[::-1] * (self.r - self.width) / self.r
+ v = np.concatenate([v1, v2, [(0, 0)]])
+ c = [*arc.codes, connector, *arc.codes[1:], Path.CLOSEPOLY]
+ else:
+ # Wedge doesn't need an inner ring
+ v = np.concatenate([arc.vertices, [(0, 0), (0, 0)]])
+ c = [*arc.codes, connector, Path.CLOSEPOLY]
+
+ # Shift and scale the wedge to the final location.
+ self._path = Path(v * self.r + self.center, c)
+
+ def set_center(self, center):
+ self._path = None
+ self.center = center
+ self.stale = True
+
+ def set_radius(self, radius):
+ self._path = None
+ self.r = radius
+ self.stale = True
+
+ def set_theta1(self, theta1):
+ self._path = None
+ self.theta1 = theta1
+ self.stale = True
+
+ def set_theta2(self, theta2):
+ self._path = None
+ self.theta2 = theta2
+ self.stale = True
+
+ def set_width(self, width):
+ self._path = None
+ self.width = width
+ self.stale = True
+
+ def get_path(self):
+ if self._path is None:
+ self._recompute_path()
+ return self._path
+
+
+# COVERAGE NOTE: Not used internally or from examples
+class Arrow(Patch):
+ """An arrow patch."""
+
+ def __str__(self):
+ return "Arrow()"
+
+ _path = Path._create_closed([
+ [0.0, 0.1], [0.0, -0.1], [0.8, -0.1], [0.8, -0.3], [1.0, 0.0],
+ [0.8, 0.3], [0.8, 0.1]])
+
+ @_docstring.dedent_interpd
+ @_api.make_keyword_only("3.6", name="width")
+ def __init__(self, x, y, dx, dy, width=1.0, **kwargs):
+ """
+ Draws an arrow from (*x*, *y*) to (*x* + *dx*, *y* + *dy*).
+ The width of the arrow is scaled by *width*.
+
+ Parameters
+ ----------
+ x : float
+ x coordinate of the arrow tail.
+ y : float
+ y coordinate of the arrow tail.
+ dx : float
+ Arrow length in the x direction.
+ dy : float
+ Arrow length in the y direction.
+ width : float, default: 1
+ Scale factor for the width of the arrow. With a default value of 1,
+ the tail width is 0.2 and head width is 0.6.
+ **kwargs
+ Keyword arguments control the `Patch` properties:
+
+ %(Patch:kwdoc)s
+
+ See Also
+ --------
+ FancyArrow
+ Patch that allows independent control of the head and tail
+ properties.
+ """
+ super().__init__(**kwargs)
+ self._patch_transform = (
+ transforms.Affine2D()
+ .scale(np.hypot(dx, dy), width)
+ .rotate(np.arctan2(dy, dx))
+ .translate(x, y)
+ .frozen())
+
+ def get_path(self):
+ return self._path
+
+ def get_patch_transform(self):
+ return self._patch_transform
+
+
+class FancyArrow(Polygon):
+ """
+ Like Arrow, but lets you set head width and head height independently.
+ """
+
+ _edge_default = True
+
+ def __str__(self):
+ return "FancyArrow()"
+
+ @_docstring.dedent_interpd
+ @_api.make_keyword_only("3.6", name="width")
+ def __init__(self, x, y, dx, dy, width=0.001, length_includes_head=False,
+ head_width=None, head_length=None, shape='full', overhang=0,
+ head_starts_at_zero=False, **kwargs):
+ """
+ Parameters
+ ----------
+ x, y : float
+ The x and y coordinates of the arrow base.
+
+ dx, dy : float
+ The length of the arrow along x and y direction.
+
+ width : float, default: 0.001
+ Width of full arrow tail.
+
+ length_includes_head : bool, default: False
+ True if head is to be counted in calculating the length.
+
+ head_width : float or None, default: 3*width
+ Total width of the full arrow head.
+
+ head_length : float or None, default: 1.5*head_width
+ Length of arrow head.
+
+ shape : {'full', 'left', 'right'}, default: 'full'
+ Draw the left-half, right-half, or full arrow.
+
+ overhang : float, default: 0
+ Fraction that the arrow is swept back (0 overhang means
+ triangular shape). Can be negative or greater than one.
+
+ head_starts_at_zero : bool, default: False
+ If True, the head starts being drawn at coordinate 0
+ instead of ending at coordinate 0.
+
+ **kwargs
+ `.Patch` properties:
+
+ %(Patch:kwdoc)s
+ """
+ self._x = x
+ self._y = y
+ self._dx = dx
+ self._dy = dy
+ self._width = width
+ self._length_includes_head = length_includes_head
+ self._head_width = head_width
+ self._head_length = head_length
+ self._shape = shape
+ self._overhang = overhang
+ self._head_starts_at_zero = head_starts_at_zero
+ self._make_verts()
+ super().__init__(self.verts, closed=True, **kwargs)
+
+ def set_data(self, *, x=None, y=None, dx=None, dy=None, width=None,
+ head_width=None, head_length=None):
+ """
+ Set `.FancyArrow` x, y, dx, dy, width, head_with, and head_length.
+ Values left as None will not be updated.
+
+ Parameters
+ ----------
+ x, y : float or None, default: None
+ The x and y coordinates of the arrow base.
+
+ dx, dy : float or None, default: None
+ The length of the arrow along x and y direction.
+
+ width : float or None, default: None
+ Width of full arrow tail.
+
+ head_width : float or None, default: None
+ Total width of the full arrow head.
+
+ head_length : float or None, default: None
+ Length of arrow head.
+ """
+ if x is not None:
+ self._x = x
+ if y is not None:
+ self._y = y
+ if dx is not None:
+ self._dx = dx
+ if dy is not None:
+ self._dy = dy
+ if width is not None:
+ self._width = width
+ if head_width is not None:
+ self._head_width = head_width
+ if head_length is not None:
+ self._head_length = head_length
+ self._make_verts()
+ self.set_xy(self.verts)
+
+ def _make_verts(self):
+ if self._head_width is None:
+ head_width = 3 * self._width
+ else:
+ head_width = self._head_width
+ if self._head_length is None:
+ head_length = 1.5 * head_width
+ else:
+ head_length = self._head_length
+
+ distance = np.hypot(self._dx, self._dy)
+
+ if self._length_includes_head:
+ length = distance
+ else:
+ length = distance + head_length
+ if not length:
+ self.verts = np.empty([0, 2]) # display nothing if empty
+ else:
+ # start by drawing horizontal arrow, point at (0, 0)
+ hw, hl = head_width, head_length
+ hs, lw = self._overhang, self._width
+ left_half_arrow = np.array([
+ [0.0, 0.0], # tip
+ [-hl, -hw / 2], # leftmost
+ [-hl * (1 - hs), -lw / 2], # meets stem
+ [-length, -lw / 2], # bottom left
+ [-length, 0],
+ ])
+ # if we're not including the head, shift up by head length
+ if not self._length_includes_head:
+ left_half_arrow += [head_length, 0]
+ # if the head starts at 0, shift up by another head length
+ if self._head_starts_at_zero:
+ left_half_arrow += [head_length / 2, 0]
+ # figure out the shape, and complete accordingly
+ if self._shape == 'left':
+ coords = left_half_arrow
+ else:
+ right_half_arrow = left_half_arrow * [1, -1]
+ if self._shape == 'right':
+ coords = right_half_arrow
+ elif self._shape == 'full':
+ # The half-arrows contain the midpoint of the stem,
+ # which we can omit from the full arrow. Including it
+ # twice caused a problem with xpdf.
+ coords = np.concatenate([left_half_arrow[:-1],
+ right_half_arrow[-2::-1]])
+ else:
+ raise ValueError(f"Got unknown shape: {self._shape!r}")
+ if distance != 0:
+ cx = self._dx / distance
+ sx = self._dy / distance
+ else:
+ # Account for division by zero
+ cx, sx = 0, 1
+ M = [[cx, sx], [-sx, cx]]
+ self.verts = np.dot(coords, M) + [
+ self._x + self._dx,
+ self._y + self._dy,
+ ]
+
+
+_docstring.interpd.update(
+ FancyArrow="\n".join(
+ (inspect.getdoc(FancyArrow.__init__) or "").splitlines()[2:]))
+
+
+class CirclePolygon(RegularPolygon):
+ """A polygon-approximation of a circle patch."""
+
+ def __str__(self):
+ s = "CirclePolygon((%g, %g), radius=%g, resolution=%d)"
+ return s % (self.xy[0], self.xy[1], self.radius, self.numvertices)
+
+ @_docstring.dedent_interpd
+ @_api.make_keyword_only("3.6", name="resolution")
+ def __init__(self, xy, radius=5,
+ resolution=20, # the number of vertices
+ ** kwargs):
+ """
+ Create a circle at *xy* = (*x*, *y*) with given *radius*.
+
+ This circle is approximated by a regular polygon with *resolution*
+ sides. For a smoother circle drawn with splines, see `Circle`.
+
+ Valid keyword arguments are:
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__(
+ xy, resolution, radius=radius, orientation=0, **kwargs)
+
+
+class Ellipse(Patch):
+ """A scale-free ellipse."""
+
+ def __str__(self):
+ pars = (self._center[0], self._center[1],
+ self.width, self.height, self.angle)
+ fmt = "Ellipse(xy=(%s, %s), width=%s, height=%s, angle=%s)"
+ return fmt % pars
+
+ @_docstring.dedent_interpd
+ @_api.make_keyword_only("3.6", name="angle")
+ def __init__(self, xy, width, height, angle=0, **kwargs):
+ """
+ Parameters
+ ----------
+ xy : (float, float)
+ xy coordinates of ellipse centre.
+ width : float
+ Total length (diameter) of horizontal axis.
+ height : float
+ Total length (diameter) of vertical axis.
+ angle : float, default: 0
+ Rotation in degrees anti-clockwise.
+
+ Notes
+ -----
+ Valid keyword arguments are:
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__(**kwargs)
+
+ self._center = xy
+ self._width, self._height = width, height
+ self._angle = angle
+ self._path = Path.unit_circle()
+ # Required for EllipseSelector with axes aspect ratio != 1
+ # The patch is defined in data coordinates and when changing the
+ # selector with square modifier and not in data coordinates, we need
+ # to correct for the aspect ratio difference between the data and
+ # display coordinate systems.
+ self._aspect_ratio_correction = 1.0
+ # Note: This cannot be calculated until this is added to an Axes
+ self._patch_transform = transforms.IdentityTransform()
+
+ def _recompute_transform(self):
+ """
+ Notes
+ -----
+ This cannot be called until after this has been added to an Axes,
+ otherwise unit conversion will fail. This makes it very important to
+ call the accessor method and not directly access the transformation
+ member variable.
+ """
+ center = (self.convert_xunits(self._center[0]),
+ self.convert_yunits(self._center[1]))
+ width = self.convert_xunits(self._width)
+ height = self.convert_yunits(self._height)
+ self._patch_transform = transforms.Affine2D() \
+ .scale(width * 0.5, height * 0.5 * self._aspect_ratio_correction) \
+ .rotate_deg(self.angle) \
+ .scale(1, 1 / self._aspect_ratio_correction) \
+ .translate(*center)
+
+ def get_path(self):
+ """Return the path of the ellipse."""
+ return self._path
+
+ def get_patch_transform(self):
+ self._recompute_transform()
+ return self._patch_transform
+
+ def set_center(self, xy):
+ """
+ Set the center of the ellipse.
+
+ Parameters
+ ----------
+ xy : (float, float)
+ """
+ self._center = xy
+ self.stale = True
+
+ def get_center(self):
+ """Return the center of the ellipse."""
+ return self._center
+
+ center = property(get_center, set_center)
+
+ def set_width(self, width):
+ """
+ Set the width of the ellipse.
+
+ Parameters
+ ----------
+ width : float
+ """
+ self._width = width
+ self.stale = True
+
+ def get_width(self):
+ """
+ Return the width of the ellipse.
+ """
+ return self._width
+
+ width = property(get_width, set_width)
+
+ def set_height(self, height):
+ """
+ Set the height of the ellipse.
+
+ Parameters
+ ----------
+ height : float
+ """
+ self._height = height
+ self.stale = True
+
+ def get_height(self):
+ """Return the height of the ellipse."""
+ return self._height
+
+ height = property(get_height, set_height)
+
+ def set_angle(self, angle):
+ """
+ Set the angle of the ellipse.
+
+ Parameters
+ ----------
+ angle : float
+ """
+ self._angle = angle
+ self.stale = True
+
+ def get_angle(self):
+ """Return the angle of the ellipse."""
+ return self._angle
+
+ angle = property(get_angle, set_angle)
+
+ def get_corners(self):
+ """
+ Return the corners of the ellipse bounding box.
+
+ The bounding box orientation is moving anti-clockwise from the
+ lower left corner defined before rotation.
+ """
+ return self.get_patch_transform().transform(
+ [(-1, -1), (1, -1), (1, 1), (-1, 1)])
+
+
+class Annulus(Patch):
+ """
+ An elliptical annulus.
+ """
+
+ @_docstring.dedent_interpd
+ def __init__(self, xy, r, width, angle=0.0, **kwargs):
+ """
+ Parameters
+ ----------
+ xy : (float, float)
+ xy coordinates of annulus centre.
+ r : float or (float, float)
+ The radius, or semi-axes:
+
+ - If float: radius of the outer circle.
+ - If two floats: semi-major and -minor axes of outer ellipse.
+ width : float
+ Width (thickness) of the annular ring. The width is measured inward
+ from the outer ellipse so that for the inner ellipse the semi-axes
+ are given by ``r - width``. *width* must be less than or equal to
+ the semi-minor axis.
+ angle : float, default: 0
+ Rotation angle in degrees (anti-clockwise from the positive
+ x-axis). Ignored for circular annuli (i.e., if *r* is a scalar).
+ **kwargs
+ Keyword arguments control the `Patch` properties:
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__(**kwargs)
+
+ self.set_radii(r)
+ self.center = xy
+ self.width = width
+ self.angle = angle
+ self._path = None
+
+ def __str__(self):
+ if self.a == self.b:
+ r = self.a
+ else:
+ r = (self.a, self.b)
+
+ return "Annulus(xy=(%s, %s), r=%s, width=%s, angle=%s)" % \
+ (*self.center, r, self.width, self.angle)
+
+ def set_center(self, xy):
+ """
+ Set the center of the annulus.
+
+ Parameters
+ ----------
+ xy : (float, float)
+ """
+ self._center = xy
+ self._path = None
+ self.stale = True
+
+ def get_center(self):
+ """Return the center of the annulus."""
+ return self._center
+
+ center = property(get_center, set_center)
+
+ def set_width(self, width):
+ """
+ Set the width (thickness) of the annulus ring.
+
+ The width is measured inwards from the outer ellipse.
+
+ Parameters
+ ----------
+ width : float
+ """
+ if min(self.a, self.b) <= width:
+ raise ValueError(
+ 'Width of annulus must be less than or equal semi-minor axis')
+
+ self._width = width
+ self._path = None
+ self.stale = True
+
+ def get_width(self):
+ """Return the width (thickness) of the annulus ring."""
+ return self._width
+
+ width = property(get_width, set_width)
+
+ def set_angle(self, angle):
+ """
+ Set the tilt angle of the annulus.
+
+ Parameters
+ ----------
+ angle : float
+ """
+ self._angle = angle
+ self._path = None
+ self.stale = True
+
+ def get_angle(self):
+ """Return the angle of the annulus."""
+ return self._angle
+
+ angle = property(get_angle, set_angle)
+
+ def set_semimajor(self, a):
+ """
+ Set the semi-major axis *a* of the annulus.
+
+ Parameters
+ ----------
+ a : float
+ """
+ self.a = float(a)
+ self._path = None
+ self.stale = True
+
+ def set_semiminor(self, b):
+ """
+ Set the semi-minor axis *b* of the annulus.
+
+ Parameters
+ ----------
+ b : float
+ """
+ self.b = float(b)
+ self._path = None
+ self.stale = True
+
+ def set_radii(self, r):
+ """
+ Set the semi-major (*a*) and semi-minor radii (*b*) of the annulus.
+
+ Parameters
+ ----------
+ r : float or (float, float)
+ The radius, or semi-axes:
+
+ - If float: radius of the outer circle.
+ - If two floats: semi-major and -minor axes of outer ellipse.
+ """
+ if np.shape(r) == (2,):
+ self.a, self.b = r
+ elif np.shape(r) == ():
+ self.a = self.b = float(r)
+ else:
+ raise ValueError("Parameter 'r' must be one or two floats.")
+
+ self._path = None
+ self.stale = True
+
+ def get_radii(self):
+ """Return the semi-major and semi-minor radii of the annulus."""
+ return self.a, self.b
+
+ radii = property(get_radii, set_radii)
+
+ def _transform_verts(self, verts, a, b):
+ return transforms.Affine2D() \
+ .scale(*self._convert_xy_units((a, b))) \
+ .rotate_deg(self.angle) \
+ .translate(*self._convert_xy_units(self.center)) \
+ .transform(verts)
+
+ def _recompute_path(self):
+ # circular arc
+ arc = Path.arc(0, 360)
+
+ # annulus needs to draw an outer ring
+ # followed by a reversed and scaled inner ring
+ a, b, w = self.a, self.b, self.width
+ v1 = self._transform_verts(arc.vertices, a, b)
+ v2 = self._transform_verts(arc.vertices[::-1], a - w, b - w)
+ v = np.vstack([v1, v2, v1[0, :], (0, 0)])
+ c = np.hstack([arc.codes, Path.MOVETO,
+ arc.codes[1:], Path.MOVETO,
+ Path.CLOSEPOLY])
+ self._path = Path(v, c)
+
+ def get_path(self):
+ if self._path is None:
+ self._recompute_path()
+ return self._path
+
+
+class Circle(Ellipse):
+ """
+ A circle patch.
+ """
+ def __str__(self):
+ pars = self.center[0], self.center[1], self.radius
+ fmt = "Circle(xy=(%g, %g), radius=%g)"
+ return fmt % pars
+
+ @_docstring.dedent_interpd
+ def __init__(self, xy, radius=5, **kwargs):
+ """
+ Create a true circle at center *xy* = (*x*, *y*) with given *radius*.
+
+ Unlike `CirclePolygon` which is a polygonal approximation, this uses
+ Bezier splines and is much closer to a scale-free circle.
+
+ Valid keyword arguments are:
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__(xy, radius * 2, radius * 2, **kwargs)
+ self.radius = radius
+
+ def set_radius(self, radius):
+ """
+ Set the radius of the circle.
+
+ Parameters
+ ----------
+ radius : float
+ """
+ self.width = self.height = 2 * radius
+ self.stale = True
+
+ def get_radius(self):
+ """Return the radius of the circle."""
+ return self.width / 2.
+
+ radius = property(get_radius, set_radius)
+
+
+class Arc(Ellipse):
+ """
+ An elliptical arc, i.e. a segment of an ellipse.
+
+ Due to internal optimizations, the arc cannot be filled.
+ """
+
+ def __str__(self):
+ pars = (self.center[0], self.center[1], self.width,
+ self.height, self.angle, self.theta1, self.theta2)
+ fmt = ("Arc(xy=(%g, %g), width=%g, "
+ "height=%g, angle=%g, theta1=%g, theta2=%g)")
+ return fmt % pars
+
+ @_docstring.dedent_interpd
+ @_api.make_keyword_only("3.6", name="angle")
+ def __init__(self, xy, width, height, angle=0.0,
+ theta1=0.0, theta2=360.0, **kwargs):
+ """
+ Parameters
+ ----------
+ xy : (float, float)
+ The center of the ellipse.
+
+ width : float
+ The length of the horizontal axis.
+
+ height : float
+ The length of the vertical axis.
+
+ angle : float
+ Rotation of the ellipse in degrees (counterclockwise).
+
+ theta1, theta2 : float, default: 0, 360
+ Starting and ending angles of the arc in degrees. These values
+ are relative to *angle*, e.g. if *angle* = 45 and *theta1* = 90
+ the absolute starting angle is 135.
+ Default *theta1* = 0, *theta2* = 360, i.e. a complete ellipse.
+ The arc is drawn in the counterclockwise direction.
+ Angles greater than or equal to 360, or smaller than 0, are
+ represented by an equivalent angle in the range [0, 360), by
+ taking the input value mod 360.
+
+ Other Parameters
+ ----------------
+ **kwargs : `~matplotlib.patches.Patch` properties
+ Most `.Patch` properties are supported as keyword arguments,
+ except *fill* and *facecolor* because filling is not supported.
+
+ %(Patch:kwdoc)s
+ """
+ fill = kwargs.setdefault('fill', False)
+ if fill:
+ raise ValueError("Arc objects can not be filled")
+
+ super().__init__(xy, width, height, angle=angle, **kwargs)
+
+ self.theta1 = theta1
+ self.theta2 = theta2
+ (self._theta1, self._theta2, self._stretched_width,
+ self._stretched_height) = self._theta_stretch()
+ self._path = Path.arc(self._theta1, self._theta2)
+
+ @artist.allow_rasterization
+ def draw(self, renderer):
+ """
+ Draw the arc to the given *renderer*.
+
+ Notes
+ -----
+ Ellipses are normally drawn using an approximation that uses
+ eight cubic Bezier splines. The error of this approximation
+ is 1.89818e-6, according to this unverified source:
+
+ Lancaster, Don. *Approximating a Circle or an Ellipse Using
+ Four Bezier Cubic Splines.*
+
+ https://www.tinaja.com/glib/ellipse4.pdf
+
+ There is a use case where very large ellipses must be drawn
+ with very high accuracy, and it is too expensive to render the
+ entire ellipse with enough segments (either splines or line
+ segments). Therefore, in the case where either radius of the
+ ellipse is large enough that the error of the spline
+ approximation will be visible (greater than one pixel offset
+ from the ideal), a different technique is used.
+
+ In that case, only the visible parts of the ellipse are drawn,
+ with each visible arc using a fixed number of spline segments
+ (8). The algorithm proceeds as follows:
+
+ 1. The points where the ellipse intersects the axes (or figure)
+ bounding box are located. (This is done by performing an inverse
+ transformation on the bbox such that it is relative to the unit
+ circle -- this makes the intersection calculation much easier than
+ doing rotated ellipse intersection directly.)
+
+ This uses the "line intersecting a circle" algorithm from:
+
+ Vince, John. *Geometry for Computer Graphics: Formulae,
+ Examples & Proofs.* London: Springer-Verlag, 2005.
+
+ 2. The angles of each of the intersection points are calculated.
+
+ 3. Proceeding counterclockwise starting in the positive
+ x-direction, each of the visible arc-segments between the
+ pairs of vertices are drawn using the Bezier arc
+ approximation technique implemented in `.Path.arc`.
+ """
+ if not self.get_visible():
+ return
+
+ self._recompute_transform()
+
+ self._update_path()
+ # Get width and height in pixels we need to use
+ # `self.get_data_transform` rather than `self.get_transform`
+ # because we want the transform from dataspace to the
+ # screen space to estimate how big the arc will be in physical
+ # units when rendered (the transform that we get via
+ # `self.get_transform()` goes from an idealized unit-radius
+ # space to screen space).
+ data_to_screen_trans = self.get_data_transform()
+ pwidth, pheight = (
+ data_to_screen_trans.transform((self._stretched_width,
+ self._stretched_height)) -
+ data_to_screen_trans.transform((0, 0)))
+ inv_error = (1.0 / 1.89818e-6) * 0.5
+
+ if pwidth < inv_error and pheight < inv_error:
+ return Patch.draw(self, renderer)
+
+ def line_circle_intersect(x0, y0, x1, y1):
+ dx = x1 - x0
+ dy = y1 - y0
+ dr2 = dx * dx + dy * dy
+ D = x0 * y1 - x1 * y0
+ D2 = D * D
+ discrim = dr2 - D2
+ if discrim >= 0.0:
+ sign_dy = np.copysign(1, dy) # +/-1, never 0.
+ sqrt_discrim = np.sqrt(discrim)
+ return np.array(
+ [[(D * dy + sign_dy * dx * sqrt_discrim) / dr2,
+ (-D * dx + abs(dy) * sqrt_discrim) / dr2],
+ [(D * dy - sign_dy * dx * sqrt_discrim) / dr2,
+ (-D * dx - abs(dy) * sqrt_discrim) / dr2]])
+ else:
+ return np.empty((0, 2))
+
+ def segment_circle_intersect(x0, y0, x1, y1):
+ epsilon = 1e-9
+ if x1 < x0:
+ x0e, x1e = x1, x0
+ else:
+ x0e, x1e = x0, x1
+ if y1 < y0:
+ y0e, y1e = y1, y0
+ else:
+ y0e, y1e = y0, y1
+ xys = line_circle_intersect(x0, y0, x1, y1)
+ xs, ys = xys.T
+ return xys[
+ (x0e - epsilon < xs) & (xs < x1e + epsilon)
+ & (y0e - epsilon < ys) & (ys < y1e + epsilon)
+ ]
+
+ # Transform the axes (or figure) box_path so that it is relative to
+ # the unit circle in the same way that it is relative to the desired
+ # ellipse.
+ box_path_transform = (
+ transforms.BboxTransformTo((self.axes or self.figure).bbox)
+ - self.get_transform())
+ box_path = Path.unit_rectangle().transformed(box_path_transform)
+
+ thetas = set()
+ # For each of the point pairs, there is a line segment
+ for p0, p1 in zip(box_path.vertices[:-1], box_path.vertices[1:]):
+ xy = segment_circle_intersect(*p0, *p1)
+ x, y = xy.T
+ # arctan2 return [-pi, pi), the rest of our angles are in
+ # [0, 360], adjust as needed.
+ theta = (np.rad2deg(np.arctan2(y, x)) + 360) % 360
+ thetas.update(
+ theta[(self._theta1 < theta) & (theta < self._theta2)])
+ thetas = sorted(thetas) + [self._theta2]
+ last_theta = self._theta1
+ theta1_rad = np.deg2rad(self._theta1)
+ inside = box_path.contains_point(
+ (np.cos(theta1_rad), np.sin(theta1_rad))
+ )
+
+ # save original path
+ path_original = self._path
+ for theta in thetas:
+ if inside:
+ self._path = Path.arc(last_theta, theta, 8)
+ Patch.draw(self, renderer)
+ inside = False
+ else:
+ inside = True
+ last_theta = theta
+
+ # restore original path
+ self._path = path_original
+
+ def _update_path(self):
+ # Compute new values and update and set new _path if any value changed
+ stretched = self._theta_stretch()
+ if any(a != b for a, b in zip(
+ stretched, (self._theta1, self._theta2, self._stretched_width,
+ self._stretched_height))):
+ (self._theta1, self._theta2, self._stretched_width,
+ self._stretched_height) = stretched
+ self._path = Path.arc(self._theta1, self._theta2)
+
+ def _theta_stretch(self):
+ # If the width and height of ellipse are not equal, take into account
+ # stretching when calculating angles to draw between
+ def theta_stretch(theta, scale):
+ theta = np.deg2rad(theta)
+ x = np.cos(theta)
+ y = np.sin(theta)
+ stheta = np.rad2deg(np.arctan2(scale * y, x))
+ # arctan2 has the range [-pi, pi], we expect [0, 2*pi]
+ return (stheta + 360) % 360
+
+ width = self.convert_xunits(self.width)
+ height = self.convert_yunits(self.height)
+ if (
+ # if we need to stretch the angles because we are distorted
+ width != height
+ # and we are not doing a full circle.
+ #
+ # 0 and 360 do not exactly round-trip through the angle
+ # stretching (due to both float precision limitations and
+ # the difference between the range of arctan2 [-pi, pi] and
+ # this method [0, 360]) so avoid doing it if we don't have to.
+ and not (self.theta1 != self.theta2 and
+ self.theta1 % 360 == self.theta2 % 360)
+ ):
+ theta1 = theta_stretch(self.theta1, width / height)
+ theta2 = theta_stretch(self.theta2, width / height)
+ return theta1, theta2, width, height
+ return self.theta1, self.theta2, width, height
+
+
+def bbox_artist(artist, renderer, props=None, fill=True):
+ """
+ A debug function to draw a rectangle around the bounding
+ box returned by an artist's `.Artist.get_window_extent`
+ to test whether the artist is returning the correct bbox.
+
+ *props* is a dict of rectangle props with the additional property
+ 'pad' that sets the padding around the bbox in points.
+ """
+ if props is None:
+ props = {}
+ props = props.copy() # don't want to alter the pad externally
+ pad = props.pop('pad', 4)
+ pad = renderer.points_to_pixels(pad)
+ bbox = artist.get_window_extent(renderer)
+ r = Rectangle(
+ xy=(bbox.x0 - pad / 2, bbox.y0 - pad / 2),
+ width=bbox.width + pad, height=bbox.height + pad,
+ fill=fill, transform=transforms.IdentityTransform(), clip_on=False)
+ r.update(props)
+ r.draw(renderer)
+
+
+def draw_bbox(bbox, renderer, color='k', trans=None):
+ """
+ A debug function to draw a rectangle around the bounding
+ box returned by an artist's `.Artist.get_window_extent`
+ to test whether the artist is returning the correct bbox.
+ """
+ r = Rectangle(xy=bbox.p0, width=bbox.width, height=bbox.height,
+ edgecolor=color, fill=False, clip_on=False)
+ if trans is not None:
+ r.set_transform(trans)
+ r.draw(renderer)
+
+
+class _Style:
+ """
+ A base class for the Styles. It is meant to be a container class,
+ where actual styles are declared as subclass of it, and it
+ provides some helper functions.
+ """
+
+ def __init_subclass__(cls):
+ # Automatically perform docstring interpolation on the subclasses:
+ # This allows listing the supported styles via
+ # - %(BoxStyle:table)s
+ # - %(ConnectionStyle:table)s
+ # - %(ArrowStyle:table)s
+ # and additionally adding .. ACCEPTS: blocks via
+ # - %(BoxStyle:table_and_accepts)s
+ # - %(ConnectionStyle:table_and_accepts)s
+ # - %(ArrowStyle:table_and_accepts)s
+ _docstring.interpd.update({
+ f"{cls.__name__}:table": cls.pprint_styles(),
+ f"{cls.__name__}:table_and_accepts": (
+ cls.pprint_styles()
+ + "\n\n .. ACCEPTS: ["
+ + "|".join(map(" '{}' ".format, cls._style_list))
+ + "]")
+ })
+
+ def __new__(cls, stylename, **kwargs):
+ """Return the instance of the subclass with the given style name."""
+ # The "class" should have the _style_list attribute, which is a mapping
+ # of style names to style classes.
+ _list = stylename.replace(" ", "").split(",")
+ _name = _list[0].lower()
+ try:
+ _cls = cls._style_list[_name]
+ except KeyError as err:
+ raise ValueError(f"Unknown style: {stylename!r}") from err
+ try:
+ _args_pair = [cs.split("=") for cs in _list[1:]]
+ _args = {k: float(v) for k, v in _args_pair}
+ except ValueError as err:
+ raise ValueError(
+ f"Incorrect style argument: {stylename!r}") from err
+ return _cls(**{**_args, **kwargs})
+
+ @classmethod
+ def get_styles(cls):
+ """Return a dictionary of available styles."""
+ return cls._style_list
+
+ @classmethod
+ def pprint_styles(cls):
+ """Return the available styles as pretty-printed string."""
+ table = [('Class', 'Name', 'Attrs'),
+ *[(cls.__name__,
+ # Add backquotes, as - and | have special meaning in reST.
+ f'``{name}``',
+ # [1:-1] drops the surrounding parentheses.
+ str(inspect.signature(cls))[1:-1] or 'None')
+ for name, cls in cls._style_list.items()]]
+ # Convert to rst table.
+ col_len = [max(len(cell) for cell in column) for column in zip(*table)]
+ table_formatstr = ' '.join('=' * cl for cl in col_len)
+ rst_table = '\n'.join([
+ '',
+ table_formatstr,
+ ' '.join(cell.ljust(cl) for cell, cl in zip(table[0], col_len)),
+ table_formatstr,
+ *[' '.join(cell.ljust(cl) for cell, cl in zip(row, col_len))
+ for row in table[1:]],
+ table_formatstr,
+ ])
+ return textwrap.indent(rst_table, prefix=' ' * 4)
+
+ @classmethod
+ def register(cls, name, style):
+ """Register a new style."""
+ if not issubclass(style, cls._Base):
+ raise ValueError("%s must be a subclass of %s" % (style,
+ cls._Base))
+ cls._style_list[name] = style
+
+
+def _register_style(style_list, cls=None, *, name=None):
+ """Class decorator that stashes a class in a (style) dictionary."""
+ if cls is None:
+ return functools.partial(_register_style, style_list, name=name)
+ style_list[name or cls.__name__.lower()] = cls
+ return cls
+
+
+@_docstring.dedent_interpd
+class BoxStyle(_Style):
+ """
+ `BoxStyle` is a container class which defines several
+ boxstyle classes, which are used for `FancyBboxPatch`.
+
+ A style object can be created as::
+
+ BoxStyle.Round(pad=0.2)
+
+ or::
+
+ BoxStyle("Round", pad=0.2)
+
+ or::
+
+ BoxStyle("Round, pad=0.2")
+
+ The following boxstyle classes are defined.
+
+ %(BoxStyle:table)s
+
+ An instance of a boxstyle class is a callable object, with the signature ::
+
+ __call__(self, x0, y0, width, height, mutation_size) -> Path
+
+ *x0*, *y0*, *width* and *height* specify the location and size of the box
+ to be drawn; *mutation_size* scales the outline properties such as padding.
+ """
+
+ _style_list = {}
+
+ @_register_style(_style_list)
+ class Square:
+ """A square box."""
+
+ def __init__(self, pad=0.3):
+ """
+ Parameters
+ ----------
+ pad : float, default: 0.3
+ The amount of padding around the original box.
+ """
+ self.pad = pad
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+ pad = mutation_size * self.pad
+ # width and height with padding added.
+ width, height = width + 2 * pad, height + 2 * pad
+ # boundary of the padded box
+ x0, y0 = x0 - pad, y0 - pad
+ x1, y1 = x0 + width, y0 + height
+ return Path._create_closed(
+ [(x0, y0), (x1, y0), (x1, y1), (x0, y1)])
+
+ @_register_style(_style_list)
+ class Circle:
+ """A circular box."""
+
+ def __init__(self, pad=0.3):
+ """
+ Parameters
+ ----------
+ pad : float, default: 0.3
+ The amount of padding around the original box.
+ """
+ self.pad = pad
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+ pad = mutation_size * self.pad
+ width, height = width + 2 * pad, height + 2 * pad
+ # boundary of the padded box
+ x0, y0 = x0 - pad, y0 - pad
+ return Path.circle((x0 + width / 2, y0 + height / 2),
+ max(width, height) / 2)
+
+ @_register_style(_style_list)
+ class Ellipse:
+ """
+ An elliptical box.
+
+ .. versionadded:: 3.7
+ """
+
+ def __init__(self, pad=0.3):
+ """
+ Parameters
+ ----------
+ pad : float, default: 0.3
+ The amount of padding around the original box.
+ """
+ self.pad = pad
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+ pad = mutation_size * self.pad
+ width, height = width + 2 * pad, height + 2 * pad
+ # boundary of the padded box
+ x0, y0 = x0 - pad, y0 - pad
+ a = width / math.sqrt(2)
+ b = height / math.sqrt(2)
+ trans = Affine2D().scale(a, b).translate(x0 + width / 2,
+ y0 + height / 2)
+ return trans.transform_path(Path.unit_circle())
+
+ @_register_style(_style_list)
+ class LArrow:
+ """A box in the shape of a left-pointing arrow."""
+
+ def __init__(self, pad=0.3):
+ """
+ Parameters
+ ----------
+ pad : float, default: 0.3
+ The amount of padding around the original box.
+ """
+ self.pad = pad
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+ # padding
+ pad = mutation_size * self.pad
+ # width and height with padding added.
+ width, height = width + 2 * pad, height + 2 * pad
+ # boundary of the padded box
+ x0, y0 = x0 - pad, y0 - pad,
+ x1, y1 = x0 + width, y0 + height
+
+ dx = (y1 - y0) / 2
+ dxx = dx / 2
+ x0 = x0 + pad / 1.4 # adjust by ~sqrt(2)
+
+ return Path._create_closed(
+ [(x0 + dxx, y0), (x1, y0), (x1, y1), (x0 + dxx, y1),
+ (x0 + dxx, y1 + dxx), (x0 - dx, y0 + dx),
+ (x0 + dxx, y0 - dxx), # arrow
+ (x0 + dxx, y0)])
+
+ @_register_style(_style_list)
+ class RArrow(LArrow):
+ """A box in the shape of a right-pointing arrow."""
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+ p = BoxStyle.LArrow.__call__(
+ self, x0, y0, width, height, mutation_size)
+ p.vertices[:, 0] = 2 * x0 + width - p.vertices[:, 0]
+ return p
+
+ @_register_style(_style_list)
+ class DArrow:
+ """A box in the shape of a two-way arrow."""
+ # Modified from LArrow to add a right arrow to the bbox.
+
+ def __init__(self, pad=0.3):
+ """
+ Parameters
+ ----------
+ pad : float, default: 0.3
+ The amount of padding around the original box.
+ """
+ self.pad = pad
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+ # padding
+ pad = mutation_size * self.pad
+ # width and height with padding added.
+ # The width is padded by the arrows, so we don't need to pad it.
+ height = height + 2 * pad
+ # boundary of the padded box
+ x0, y0 = x0 - pad, y0 - pad
+ x1, y1 = x0 + width, y0 + height
+
+ dx = (y1 - y0) / 2
+ dxx = dx / 2
+ x0 = x0 + pad / 1.4 # adjust by ~sqrt(2)
+
+ return Path._create_closed([
+ (x0 + dxx, y0), (x1, y0), # bot-segment
+ (x1, y0 - dxx), (x1 + dx + dxx, y0 + dx),
+ (x1, y1 + dxx), # right-arrow
+ (x1, y1), (x0 + dxx, y1), # top-segment
+ (x0 + dxx, y1 + dxx), (x0 - dx, y0 + dx),
+ (x0 + dxx, y0 - dxx), # left-arrow
+ (x0 + dxx, y0)])
+
+ @_register_style(_style_list)
+ class Round:
+ """A box with round corners."""
+
+ def __init__(self, pad=0.3, rounding_size=None):
+ """
+ Parameters
+ ----------
+ pad : float, default: 0.3
+ The amount of padding around the original box.
+ rounding_size : float, default: *pad*
+ Radius of the corners.
+ """
+ self.pad = pad
+ self.rounding_size = rounding_size
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+
+ # padding
+ pad = mutation_size * self.pad
+
+ # size of the rounding corner
+ if self.rounding_size:
+ dr = mutation_size * self.rounding_size
+ else:
+ dr = pad
+
+ width, height = width + 2 * pad, height + 2 * pad
+
+ x0, y0 = x0 - pad, y0 - pad,
+ x1, y1 = x0 + width, y0 + height
+
+ # Round corners are implemented as quadratic Bezier, e.g.,
+ # [(x0, y0-dr), (x0, y0), (x0+dr, y0)] for lower left corner.
+ cp = [(x0 + dr, y0),
+ (x1 - dr, y0),
+ (x1, y0), (x1, y0 + dr),
+ (x1, y1 - dr),
+ (x1, y1), (x1 - dr, y1),
+ (x0 + dr, y1),
+ (x0, y1), (x0, y1 - dr),
+ (x0, y0 + dr),
+ (x0, y0), (x0 + dr, y0),
+ (x0 + dr, y0)]
+
+ com = [Path.MOVETO,
+ Path.LINETO,
+ Path.CURVE3, Path.CURVE3,
+ Path.LINETO,
+ Path.CURVE3, Path.CURVE3,
+ Path.LINETO,
+ Path.CURVE3, Path.CURVE3,
+ Path.LINETO,
+ Path.CURVE3, Path.CURVE3,
+ Path.CLOSEPOLY]
+
+ return Path(cp, com)
+
+ @_register_style(_style_list)
+ class Round4:
+ """A box with rounded edges."""
+
+ def __init__(self, pad=0.3, rounding_size=None):
+ """
+ Parameters
+ ----------
+ pad : float, default: 0.3
+ The amount of padding around the original box.
+ rounding_size : float, default: *pad*/2
+ Rounding of edges.
+ """
+ self.pad = pad
+ self.rounding_size = rounding_size
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+
+ # padding
+ pad = mutation_size * self.pad
+
+ # Rounding size; defaults to half of the padding.
+ if self.rounding_size:
+ dr = mutation_size * self.rounding_size
+ else:
+ dr = pad / 2.
+
+ width = width + 2 * pad - 2 * dr
+ height = height + 2 * pad - 2 * dr
+
+ x0, y0 = x0 - pad + dr, y0 - pad + dr,
+ x1, y1 = x0 + width, y0 + height
+
+ cp = [(x0, y0),
+ (x0 + dr, y0 - dr), (x1 - dr, y0 - dr), (x1, y0),
+ (x1 + dr, y0 + dr), (x1 + dr, y1 - dr), (x1, y1),
+ (x1 - dr, y1 + dr), (x0 + dr, y1 + dr), (x0, y1),
+ (x0 - dr, y1 - dr), (x0 - dr, y0 + dr), (x0, y0),
+ (x0, y0)]
+
+ com = [Path.MOVETO,
+ Path.CURVE4, Path.CURVE4, Path.CURVE4,
+ Path.CURVE4, Path.CURVE4, Path.CURVE4,
+ Path.CURVE4, Path.CURVE4, Path.CURVE4,
+ Path.CURVE4, Path.CURVE4, Path.CURVE4,
+ Path.CLOSEPOLY]
+
+ return Path(cp, com)
+
+ @_register_style(_style_list)
+ class Sawtooth:
+ """A box with a sawtooth outline."""
+
+ def __init__(self, pad=0.3, tooth_size=None):
+ """
+ Parameters
+ ----------
+ pad : float, default: 0.3
+ The amount of padding around the original box.
+ tooth_size : float, default: *pad*/2
+ Size of the sawtooth.
+ """
+ self.pad = pad
+ self.tooth_size = tooth_size
+
+ def _get_sawtooth_vertices(self, x0, y0, width, height, mutation_size):
+
+ # padding
+ pad = mutation_size * self.pad
+
+ # size of sawtooth
+ if self.tooth_size is None:
+ tooth_size = self.pad * .5 * mutation_size
+ else:
+ tooth_size = self.tooth_size * mutation_size
+
+ hsz = tooth_size / 2
+ width = width + 2 * pad - tooth_size
+ height = height + 2 * pad - tooth_size
+
+ # the sizes of the vertical and horizontal sawtooth are
+ # separately adjusted to fit the given box size.
+ dsx_n = round((width - tooth_size) / (tooth_size * 2)) * 2
+ dsx = (width - tooth_size) / dsx_n
+ dsy_n = round((height - tooth_size) / (tooth_size * 2)) * 2
+ dsy = (height - tooth_size) / dsy_n
+
+ x0, y0 = x0 - pad + hsz, y0 - pad + hsz
+ x1, y1 = x0 + width, y0 + height
+
+ xs = [
+ x0, *np.linspace(x0 + hsz, x1 - hsz, 2 * dsx_n + 1), # bottom
+ *([x1, x1 + hsz, x1, x1 - hsz] * dsy_n)[:2*dsy_n+2], # right
+ x1, *np.linspace(x1 - hsz, x0 + hsz, 2 * dsx_n + 1), # top
+ *([x0, x0 - hsz, x0, x0 + hsz] * dsy_n)[:2*dsy_n+2], # left
+ ]
+ ys = [
+ *([y0, y0 - hsz, y0, y0 + hsz] * dsx_n)[:2*dsx_n+2], # bottom
+ y0, *np.linspace(y0 + hsz, y1 - hsz, 2 * dsy_n + 1), # right
+ *([y1, y1 + hsz, y1, y1 - hsz] * dsx_n)[:2*dsx_n+2], # top
+ y1, *np.linspace(y1 - hsz, y0 + hsz, 2 * dsy_n + 1), # left
+ ]
+
+ return [*zip(xs, ys), (xs[0], ys[0])]
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+ saw_vertices = self._get_sawtooth_vertices(x0, y0, width,
+ height, mutation_size)
+ return Path(saw_vertices, closed=True)
+
+ @_register_style(_style_list)
+ class Roundtooth(Sawtooth):
+ """A box with a rounded sawtooth outline."""
+
+ def __call__(self, x0, y0, width, height, mutation_size):
+ saw_vertices = self._get_sawtooth_vertices(x0, y0,
+ width, height,
+ mutation_size)
+ # Add a trailing vertex to allow us to close the polygon correctly
+ saw_vertices = np.concatenate([saw_vertices, [saw_vertices[0]]])
+ codes = ([Path.MOVETO] +
+ [Path.CURVE3, Path.CURVE3] * ((len(saw_vertices)-1)//2) +
+ [Path.CLOSEPOLY])
+ return Path(saw_vertices, codes)
+
+
+@_docstring.dedent_interpd
+class ConnectionStyle(_Style):
+ """
+ `ConnectionStyle` is a container class which defines
+ several connectionstyle classes, which is used to create a path
+ between two points. These are mainly used with `FancyArrowPatch`.
+
+ A connectionstyle object can be either created as::
+
+ ConnectionStyle.Arc3(rad=0.2)
+
+ or::
+
+ ConnectionStyle("Arc3", rad=0.2)
+
+ or::
+
+ ConnectionStyle("Arc3, rad=0.2")
+
+ The following classes are defined
+
+ %(ConnectionStyle:table)s
+
+ An instance of any connection style class is a callable object,
+ whose call signature is::
+
+ __call__(self, posA, posB,
+ patchA=None, patchB=None,
+ shrinkA=2., shrinkB=2.)
+
+ and it returns a `.Path` instance. *posA* and *posB* are
+ tuples of (x, y) coordinates of the two points to be
+ connected. *patchA* (or *patchB*) is given, the returned path is
+ clipped so that it start (or end) from the boundary of the
+ patch. The path is further shrunk by *shrinkA* (or *shrinkB*)
+ which is given in points.
+ """
+
+ _style_list = {}
+
+ class _Base:
+ """
+ A base class for connectionstyle classes. The subclass needs
+ to implement a *connect* method whose call signature is::
+
+ connect(posA, posB)
+
+ where posA and posB are tuples of x, y coordinates to be
+ connected. The method needs to return a path connecting two
+ points. This base class defines a __call__ method, and a few
+ helper methods.
+ """
+
+ @_api.deprecated("3.7")
+ class SimpleEvent:
+ def __init__(self, xy):
+ self.x, self.y = xy
+
+ def _in_patch(self, patch):
+ """
+ Return a predicate function testing whether a point *xy* is
+ contained in *patch*.
+ """
+ return lambda xy: patch.contains(
+ SimpleNamespace(x=xy[0], y=xy[1]))[0]
+
+ def _clip(self, path, in_start, in_stop):
+ """
+ Clip *path* at its start by the region where *in_start* returns
+ True, and at its stop by the region where *in_stop* returns True.
+
+ The original path is assumed to start in the *in_start* region and
+ to stop in the *in_stop* region.
+ """
+ if in_start:
+ try:
+ _, path = split_path_inout(path, in_start)
+ except ValueError:
+ pass
+ if in_stop:
+ try:
+ path, _ = split_path_inout(path, in_stop)
+ except ValueError:
+ pass
+ return path
+
+ def __call__(self, posA, posB,
+ shrinkA=2., shrinkB=2., patchA=None, patchB=None):
+ """
+ Call the *connect* method to create a path between *posA* and
+ *posB*; then clip and shrink the path.
+ """
+ path = self.connect(posA, posB)
+ path = self._clip(
+ path,
+ self._in_patch(patchA) if patchA else None,
+ self._in_patch(patchB) if patchB else None,
+ )
+ path = self._clip(
+ path,
+ inside_circle(*path.vertices[0], shrinkA) if shrinkA else None,
+ inside_circle(*path.vertices[-1], shrinkB) if shrinkB else None
+ )
+ return path
+
+ @_register_style(_style_list)
+ class Arc3(_Base):
+ """
+ Creates a simple quadratic Bézier curve between two
+ points. The curve is created so that the middle control point
+ (C1) is located at the same distance from the start (C0) and
+ end points(C2) and the distance of the C1 to the line
+ connecting C0-C2 is *rad* times the distance of C0-C2.
+ """
+
+ def __init__(self, rad=0.):
+ """
+ Parameters
+ ----------
+ rad : float
+ Curvature of the curve.
+ """
+ self.rad = rad
+
+ def connect(self, posA, posB):
+ x1, y1 = posA
+ x2, y2 = posB
+ x12, y12 = (x1 + x2) / 2., (y1 + y2) / 2.
+ dx, dy = x2 - x1, y2 - y1
+
+ f = self.rad
+
+ cx, cy = x12 + f * dy, y12 - f * dx
+
+ vertices = [(x1, y1),
+ (cx, cy),
+ (x2, y2)]
+ codes = [Path.MOVETO,
+ Path.CURVE3,
+ Path.CURVE3]
+
+ return Path(vertices, codes)
+
+ @_register_style(_style_list)
+ class Angle3(_Base):
+ """
+ Creates a simple quadratic Bézier curve between two points. The middle
+ control point is placed at the intersecting point of two lines which
+ cross the start and end point, and have a slope of *angleA* and
+ *angleB*, respectively.
+ """
+
+ def __init__(self, angleA=90, angleB=0):
+ """
+ Parameters
+ ----------
+ angleA : float
+ Starting angle of the path.
+
+ angleB : float
+ Ending angle of the path.
+ """
+
+ self.angleA = angleA
+ self.angleB = angleB
+
+ def connect(self, posA, posB):
+ x1, y1 = posA
+ x2, y2 = posB
+
+ cosA = math.cos(math.radians(self.angleA))
+ sinA = math.sin(math.radians(self.angleA))
+ cosB = math.cos(math.radians(self.angleB))
+ sinB = math.sin(math.radians(self.angleB))
+
+ cx, cy = get_intersection(x1, y1, cosA, sinA,
+ x2, y2, cosB, sinB)
+
+ vertices = [(x1, y1), (cx, cy), (x2, y2)]
+ codes = [Path.MOVETO, Path.CURVE3, Path.CURVE3]
+
+ return Path(vertices, codes)
+
+ @_register_style(_style_list)
+ class Angle(_Base):
+ """
+ Creates a piecewise continuous quadratic Bézier path between two
+ points. The path has a one passing-through point placed at the
+ intersecting point of two lines which cross the start and end point,
+ and have a slope of *angleA* and *angleB*, respectively.
+ The connecting edges are rounded with *rad*.
+ """
+
+ def __init__(self, angleA=90, angleB=0, rad=0.):
+ """
+ Parameters
+ ----------
+ angleA : float
+ Starting angle of the path.
+
+ angleB : float
+ Ending angle of the path.
+
+ rad : float
+ Rounding radius of the edge.
+ """
+
+ self.angleA = angleA
+ self.angleB = angleB
+
+ self.rad = rad
+
+ def connect(self, posA, posB):
+ x1, y1 = posA
+ x2, y2 = posB
+
+ cosA = math.cos(math.radians(self.angleA))
+ sinA = math.sin(math.radians(self.angleA))
+ cosB = math.cos(math.radians(self.angleB))
+ sinB = math.sin(math.radians(self.angleB))
+
+ cx, cy = get_intersection(x1, y1, cosA, sinA,
+ x2, y2, cosB, sinB)
+
+ vertices = [(x1, y1)]
+ codes = [Path.MOVETO]
+
+ if self.rad == 0.:
+ vertices.append((cx, cy))
+ codes.append(Path.LINETO)
+ else:
+ dx1, dy1 = x1 - cx, y1 - cy
+ d1 = np.hypot(dx1, dy1)
+ f1 = self.rad / d1
+ dx2, dy2 = x2 - cx, y2 - cy
+ d2 = np.hypot(dx2, dy2)
+ f2 = self.rad / d2
+ vertices.extend([(cx + dx1 * f1, cy + dy1 * f1),
+ (cx, cy),
+ (cx + dx2 * f2, cy + dy2 * f2)])
+ codes.extend([Path.LINETO, Path.CURVE3, Path.CURVE3])
+
+ vertices.append((x2, y2))
+ codes.append(Path.LINETO)
+
+ return Path(vertices, codes)
+
+ @_register_style(_style_list)
+ class Arc(_Base):
+ """
+ Creates a piecewise continuous quadratic Bézier path between two
+ points. The path can have two passing-through points, a
+ point placed at the distance of *armA* and angle of *angleA* from
+ point A, another point with respect to point B. The edges are
+ rounded with *rad*.
+ """
+
+ def __init__(self, angleA=0, angleB=0, armA=None, armB=None, rad=0.):
+ """
+ Parameters
+ ----------
+ angleA : float
+ Starting angle of the path.
+
+ angleB : float
+ Ending angle of the path.
+
+ armA : float or None
+ Length of the starting arm.
+
+ armB : float or None
+ Length of the ending arm.
+
+ rad : float
+ Rounding radius of the edges.
+ """
+
+ self.angleA = angleA
+ self.angleB = angleB
+ self.armA = armA
+ self.armB = armB
+
+ self.rad = rad
+
+ def connect(self, posA, posB):
+ x1, y1 = posA
+ x2, y2 = posB
+
+ vertices = [(x1, y1)]
+ rounded = []
+ codes = [Path.MOVETO]
+
+ if self.armA:
+ cosA = math.cos(math.radians(self.angleA))
+ sinA = math.sin(math.radians(self.angleA))
+ # x_armA, y_armB
+ d = self.armA - self.rad
+ rounded.append((x1 + d * cosA, y1 + d * sinA))
+ d = self.armA
+ rounded.append((x1 + d * cosA, y1 + d * sinA))
+
+ if self.armB:
+ cosB = math.cos(math.radians(self.angleB))
+ sinB = math.sin(math.radians(self.angleB))
+ x_armB, y_armB = x2 + self.armB * cosB, y2 + self.armB * sinB
+
+ if rounded:
+ xp, yp = rounded[-1]
+ dx, dy = x_armB - xp, y_armB - yp
+ dd = (dx * dx + dy * dy) ** .5
+
+ rounded.append((xp + self.rad * dx / dd,
+ yp + self.rad * dy / dd))
+ vertices.extend(rounded)
+ codes.extend([Path.LINETO,
+ Path.CURVE3,
+ Path.CURVE3])
+ else:
+ xp, yp = vertices[-1]
+ dx, dy = x_armB - xp, y_armB - yp
+ dd = (dx * dx + dy * dy) ** .5
+
+ d = dd - self.rad
+ rounded = [(xp + d * dx / dd, yp + d * dy / dd),
+ (x_armB, y_armB)]
+
+ if rounded:
+ xp, yp = rounded[-1]
+ dx, dy = x2 - xp, y2 - yp
+ dd = (dx * dx + dy * dy) ** .5
+
+ rounded.append((xp + self.rad * dx / dd,
+ yp + self.rad * dy / dd))
+ vertices.extend(rounded)
+ codes.extend([Path.LINETO,
+ Path.CURVE3,
+ Path.CURVE3])
+
+ vertices.append((x2, y2))
+ codes.append(Path.LINETO)
+
+ return Path(vertices, codes)
+
+ @_register_style(_style_list)
+ class Bar(_Base):
+ """
+ A line with *angle* between A and B with *armA* and *armB*. One of the
+ arms is extended so that they are connected in a right angle. The
+ length of *armA* is determined by (*armA* + *fraction* x AB distance).
+ Same for *armB*.
+ """
+
+ def __init__(self, armA=0., armB=0., fraction=0.3, angle=None):
+ """
+ Parameters
+ ----------
+ armA : float
+ Minimum length of armA.
+
+ armB : float
+ Minimum length of armB.
+
+ fraction : float
+ A fraction of the distance between two points that will be
+ added to armA and armB.
+
+ angle : float or None
+ Angle of the connecting line (if None, parallel to A and B).
+ """
+ self.armA = armA
+ self.armB = armB
+ self.fraction = fraction
+ self.angle = angle
+
+ def connect(self, posA, posB):
+ x1, y1 = posA
+ x20, y20 = x2, y2 = posB
+
+ theta1 = math.atan2(y2 - y1, x2 - x1)
+ dx, dy = x2 - x1, y2 - y1
+ dd = (dx * dx + dy * dy) ** .5
+ ddx, ddy = dx / dd, dy / dd
+
+ armA, armB = self.armA, self.armB
+
+ if self.angle is not None:
+ theta0 = np.deg2rad(self.angle)
+ dtheta = theta1 - theta0
+ dl = dd * math.sin(dtheta)
+ dL = dd * math.cos(dtheta)
+ x2, y2 = x1 + dL * math.cos(theta0), y1 + dL * math.sin(theta0)
+ armB = armB - dl
+
+ # update
+ dx, dy = x2 - x1, y2 - y1
+ dd2 = (dx * dx + dy * dy) ** .5
+ ddx, ddy = dx / dd2, dy / dd2
+
+ arm = max(armA, armB)
+ f = self.fraction * dd + arm
+
+ cx1, cy1 = x1 + f * ddy, y1 - f * ddx
+ cx2, cy2 = x2 + f * ddy, y2 - f * ddx
+
+ vertices = [(x1, y1),
+ (cx1, cy1),
+ (cx2, cy2),
+ (x20, y20)]
+ codes = [Path.MOVETO,
+ Path.LINETO,
+ Path.LINETO,
+ Path.LINETO]
+
+ return Path(vertices, codes)
+
+
+def _point_along_a_line(x0, y0, x1, y1, d):
+ """
+ Return the point on the line connecting (*x0*, *y0*) -- (*x1*, *y1*) whose
+ distance from (*x0*, *y0*) is *d*.
+ """
+ dx, dy = x0 - x1, y0 - y1
+ ff = d / (dx * dx + dy * dy) ** .5
+ x2, y2 = x0 - ff * dx, y0 - ff * dy
+
+ return x2, y2
+
+
+@_docstring.dedent_interpd
+class ArrowStyle(_Style):
+ """
+ `ArrowStyle` is a container class which defines several
+ arrowstyle classes, which is used to create an arrow path along a
+ given path. These are mainly used with `FancyArrowPatch`.
+
+ An arrowstyle object can be either created as::
+
+ ArrowStyle.Fancy(head_length=.4, head_width=.4, tail_width=.4)
+
+ or::
+
+ ArrowStyle("Fancy", head_length=.4, head_width=.4, tail_width=.4)
+
+ or::
+
+ ArrowStyle("Fancy, head_length=.4, head_width=.4, tail_width=.4")
+
+ The following classes are defined
+
+ %(ArrowStyle:table)s
+
+ For an overview of the visual appearance, see
+ :doc:`/gallery/text_labels_and_annotations/fancyarrow_demo`.
+
+ An instance of any arrow style class is a callable object,
+ whose call signature is::
+
+ __call__(self, path, mutation_size, linewidth, aspect_ratio=1.)
+
+ and it returns a tuple of a `.Path` instance and a boolean
+ value. *path* is a `.Path` instance along which the arrow
+ will be drawn. *mutation_size* and *aspect_ratio* have the same
+ meaning as in `BoxStyle`. *linewidth* is a line width to be
+ stroked. This is meant to be used to correct the location of the
+ head so that it does not overshoot the destination point, but not all
+ classes support it.
+
+ Notes
+ -----
+ *angleA* and *angleB* specify the orientation of the bracket, as either a
+ clockwise or counterclockwise angle depending on the arrow type. 0 degrees
+ means perpendicular to the line connecting the arrow's head and tail.
+
+ .. plot:: gallery/text_labels_and_annotations/angles_on_bracket_arrows.py
+ """
+
+ _style_list = {}
+
+ class _Base:
+ """
+ Arrow Transmuter Base class
+
+ ArrowTransmuterBase and its derivatives are used to make a fancy
+ arrow around a given path. The __call__ method returns a path
+ (which will be used to create a PathPatch instance) and a boolean
+ value indicating the path is open therefore is not fillable. This
+ class is not an artist and actual drawing of the fancy arrow is
+ done by the FancyArrowPatch class.
+ """
+
+ # The derived classes are required to be able to be initialized
+ # w/o arguments, i.e., all its argument (except self) must have
+ # the default values.
+
+ @staticmethod
+ def ensure_quadratic_bezier(path):
+ """
+ Some ArrowStyle classes only works with a simple quadratic
+ Bézier curve (created with `.ConnectionStyle.Arc3` or
+ `.ConnectionStyle.Angle3`). This static method checks if the
+ provided path is a simple quadratic Bézier curve and returns its
+ control points if true.
+ """
+ segments = list(path.iter_segments())
+ if (len(segments) != 2 or segments[0][1] != Path.MOVETO or
+ segments[1][1] != Path.CURVE3):
+ raise ValueError(
+ "'path' is not a valid quadratic Bezier curve")
+ return [*segments[0][0], *segments[1][0]]
+
+ def transmute(self, path, mutation_size, linewidth):
+ """
+ The transmute method is the very core of the ArrowStyle class and
+ must be overridden in the subclasses. It receives the *path*
+ object along which the arrow will be drawn, and the
+ *mutation_size*, with which the arrow head etc. will be scaled.
+ The *linewidth* may be used to adjust the path so that it does not
+ pass beyond the given points. It returns a tuple of a `.Path`
+ instance and a boolean. The boolean value indicate whether the
+ path can be filled or not. The return value can also be a list of
+ paths and list of booleans of the same length.
+ """
+ raise NotImplementedError('Derived must override')
+
+ def __call__(self, path, mutation_size, linewidth,
+ aspect_ratio=1.):
+ """
+ The __call__ method is a thin wrapper around the transmute method
+ and takes care of the aspect ratio.
+ """
+
+ if aspect_ratio is not None:
+ # Squeeze the given height by the aspect_ratio
+ vertices = path.vertices / [1, aspect_ratio]
+ path_shrunk = Path(vertices, path.codes)
+ # call transmute method with squeezed height.
+ path_mutated, fillable = self.transmute(path_shrunk,
+ mutation_size,
+ linewidth)
+ if np.iterable(fillable):
+ # Restore the height
+ path_list = [Path(p.vertices * [1, aspect_ratio], p.codes)
+ for p in path_mutated]
+ return path_list, fillable
+ else:
+ return path_mutated, fillable
+ else:
+ return self.transmute(path, mutation_size, linewidth)
+
+ class _Curve(_Base):
+ """
+ A simple arrow which will work with any path instance. The
+ returned path is the concatenation of the original path, and at
+ most two paths representing the arrow head or bracket at the start
+ point and at the end point. The arrow heads can be either open
+ or closed.
+ """
+
+ arrow = "-"
+ fillbegin = fillend = False # Whether arrows are filled.
+
+ def __init__(self, head_length=.4, head_width=.2, widthA=1., widthB=1.,
+ lengthA=0.2, lengthB=0.2, angleA=0, angleB=0, scaleA=None,
+ scaleB=None):
+ """
+ Parameters
+ ----------
+ head_length : float, default: 0.4
+ Length of the arrow head, relative to *mutation_size*.
+ head_width : float, default: 0.2
+ Width of the arrow head, relative to *mutation_size*.
+ widthA, widthB : float, default: 1.0
+ Width of the bracket.
+ lengthA, lengthB : float, default: 0.2
+ Length of the bracket.
+ angleA, angleB : float, default: 0
+ Orientation of the bracket, as a counterclockwise angle.
+ 0 degrees means perpendicular to the line.
+ scaleA, scaleB : float, default: *mutation_size*
+ The scale of the brackets.
+ """
+
+ self.head_length, self.head_width = head_length, head_width
+ self.widthA, self.widthB = widthA, widthB
+ self.lengthA, self.lengthB = lengthA, lengthB
+ self.angleA, self.angleB = angleA, angleB
+ self.scaleA, self.scaleB = scaleA, scaleB
+
+ self._beginarrow_head = False
+ self._beginarrow_bracket = False
+ self._endarrow_head = False
+ self._endarrow_bracket = False
+
+ if "-" not in self.arrow:
+ raise ValueError("arrow must have the '-' between "
+ "the two heads")
+
+ beginarrow, endarrow = self.arrow.split("-", 1)
+
+ if beginarrow == "<":
+ self._beginarrow_head = True
+ self._beginarrow_bracket = False
+ elif beginarrow == "<|":
+ self._beginarrow_head = True
+ self._beginarrow_bracket = False
+ self.fillbegin = True
+ elif beginarrow in ("]", "|"):
+ self._beginarrow_head = False
+ self._beginarrow_bracket = True
+
+ if endarrow == ">":
+ self._endarrow_head = True
+ self._endarrow_bracket = False
+ elif endarrow == "|>":
+ self._endarrow_head = True
+ self._endarrow_bracket = False
+ self.fillend = True
+ elif endarrow in ("[", "|"):
+ self._endarrow_head = False
+ self._endarrow_bracket = True
+
+ super().__init__()
+
+ def _get_arrow_wedge(self, x0, y0, x1, y1,
+ head_dist, cos_t, sin_t, linewidth):
+ """
+ Return the paths for arrow heads. Since arrow lines are
+ drawn with capstyle=projected, The arrow goes beyond the
+ desired point. This method also returns the amount of the path
+ to be shrunken so that it does not overshoot.
+ """
+
+ # arrow from x0, y0 to x1, y1
+ dx, dy = x0 - x1, y0 - y1
+
+ cp_distance = np.hypot(dx, dy)
+
+ # pad_projected : amount of pad to account the
+ # overshooting of the projection of the wedge
+ pad_projected = (.5 * linewidth / sin_t)
+
+ # Account for division by zero
+ if cp_distance == 0:
+ cp_distance = 1
+
+ # apply pad for projected edge
+ ddx = pad_projected * dx / cp_distance
+ ddy = pad_projected * dy / cp_distance
+
+ # offset for arrow wedge
+ dx = dx / cp_distance * head_dist
+ dy = dy / cp_distance * head_dist
+
+ dx1, dy1 = cos_t * dx + sin_t * dy, -sin_t * dx + cos_t * dy
+ dx2, dy2 = cos_t * dx - sin_t * dy, sin_t * dx + cos_t * dy
+
+ vertices_arrow = [(x1 + ddx + dx1, y1 + ddy + dy1),
+ (x1 + ddx, y1 + ddy),
+ (x1 + ddx + dx2, y1 + ddy + dy2)]
+ codes_arrow = [Path.MOVETO,
+ Path.LINETO,
+ Path.LINETO]
+
+ return vertices_arrow, codes_arrow, ddx, ddy
+
+ def _get_bracket(self, x0, y0,
+ x1, y1, width, length, angle):
+
+ cos_t, sin_t = get_cos_sin(x1, y1, x0, y0)
+
+ # arrow from x0, y0 to x1, y1
+ from matplotlib.bezier import get_normal_points
+ x1, y1, x2, y2 = get_normal_points(x0, y0, cos_t, sin_t, width)
+
+ dx, dy = length * cos_t, length * sin_t
+
+ vertices_arrow = [(x1 + dx, y1 + dy),
+ (x1, y1),
+ (x2, y2),
+ (x2 + dx, y2 + dy)]
+ codes_arrow = [Path.MOVETO,
+ Path.LINETO,
+ Path.LINETO,
+ Path.LINETO]
+
+ if angle:
+ trans = transforms.Affine2D().rotate_deg_around(x0, y0, angle)
+ vertices_arrow = trans.transform(vertices_arrow)
+
+ return vertices_arrow, codes_arrow
+
+ def transmute(self, path, mutation_size, linewidth):
+ # docstring inherited
+ if self._beginarrow_head or self._endarrow_head:
+ head_length = self.head_length * mutation_size
+ head_width = self.head_width * mutation_size
+ head_dist = np.hypot(head_length, head_width)
+ cos_t, sin_t = head_length / head_dist, head_width / head_dist
+
+ scaleA = mutation_size if self.scaleA is None else self.scaleA
+ scaleB = mutation_size if self.scaleB is None else self.scaleB
+
+ # begin arrow
+ x0, y0 = path.vertices[0]
+ x1, y1 = path.vertices[1]
+
+ # If there is no room for an arrow and a line, then skip the arrow
+ has_begin_arrow = self._beginarrow_head and (x0, y0) != (x1, y1)
+ verticesA, codesA, ddxA, ddyA = (
+ self._get_arrow_wedge(x1, y1, x0, y0,
+ head_dist, cos_t, sin_t, linewidth)
+ if has_begin_arrow
+ else ([], [], 0, 0)
+ )
+
+ # end arrow
+ x2, y2 = path.vertices[-2]
+ x3, y3 = path.vertices[-1]
+
+ # If there is no room for an arrow and a line, then skip the arrow
+ has_end_arrow = self._endarrow_head and (x2, y2) != (x3, y3)
+ verticesB, codesB, ddxB, ddyB = (
+ self._get_arrow_wedge(x2, y2, x3, y3,
+ head_dist, cos_t, sin_t, linewidth)
+ if has_end_arrow
+ else ([], [], 0, 0)
+ )
+
+ # This simple code will not work if ddx, ddy is greater than the
+ # separation between vertices.
+ paths = [Path(np.concatenate([[(x0 + ddxA, y0 + ddyA)],
+ path.vertices[1:-1],
+ [(x3 + ddxB, y3 + ddyB)]]),
+ path.codes)]
+ fills = [False]
+
+ if has_begin_arrow:
+ if self.fillbegin:
+ paths.append(
+ Path([*verticesA, (0, 0)], [*codesA, Path.CLOSEPOLY]))
+ fills.append(True)
+ else:
+ paths.append(Path(verticesA, codesA))
+ fills.append(False)
+ elif self._beginarrow_bracket:
+ x0, y0 = path.vertices[0]
+ x1, y1 = path.vertices[1]
+ verticesA, codesA = self._get_bracket(x0, y0, x1, y1,
+ self.widthA * scaleA,
+ self.lengthA * scaleA,
+ self.angleA)
+
+ paths.append(Path(verticesA, codesA))
+ fills.append(False)
+
+ if has_end_arrow:
+ if self.fillend:
+ fills.append(True)
+ paths.append(
+ Path([*verticesB, (0, 0)], [*codesB, Path.CLOSEPOLY]))
+ else:
+ fills.append(False)
+ paths.append(Path(verticesB, codesB))
+ elif self._endarrow_bracket:
+ x0, y0 = path.vertices[-1]
+ x1, y1 = path.vertices[-2]
+ verticesB, codesB = self._get_bracket(x0, y0, x1, y1,
+ self.widthB * scaleB,
+ self.lengthB * scaleB,
+ self.angleB)
+
+ paths.append(Path(verticesB, codesB))
+ fills.append(False)
+
+ return paths, fills
+
+ @_register_style(_style_list, name="-")
+ class Curve(_Curve):
+ """A simple curve without any arrow head."""
+
+ def __init__(self): # hide head_length, head_width
+ # These attributes (whose values come from backcompat) only matter
+ # if someone modifies beginarrow/etc. on an ArrowStyle instance.
+ super().__init__(head_length=.2, head_width=.1)
+
+ @_register_style(_style_list, name="<-")
+ class CurveA(_Curve):
+ """An arrow with a head at its start point."""
+ arrow = "<-"
+
+ @_register_style(_style_list, name="->")
+ class CurveB(_Curve):
+ """An arrow with a head at its end point."""
+ arrow = "->"
+
+ @_register_style(_style_list, name="<->")
+ class CurveAB(_Curve):
+ """An arrow with heads both at the start and the end point."""
+ arrow = "<->"
+
+ @_register_style(_style_list, name="<|-")
+ class CurveFilledA(_Curve):
+ """An arrow with filled triangle head at the start."""
+ arrow = "<|-"
+
+ @_register_style(_style_list, name="-|>")
+ class CurveFilledB(_Curve):
+ """An arrow with filled triangle head at the end."""
+ arrow = "-|>"
+
+ @_register_style(_style_list, name="<|-|>")
+ class CurveFilledAB(_Curve):
+ """An arrow with filled triangle heads at both ends."""
+ arrow = "<|-|>"
+
+ @_register_style(_style_list, name="]-")
+ class BracketA(_Curve):
+ """An arrow with an outward square bracket at its start."""
+ arrow = "]-"
+
+ def __init__(self, widthA=1., lengthA=0.2, angleA=0):
+ """
+ Parameters
+ ----------
+ widthA : float, default: 1.0
+ Width of the bracket.
+ lengthA : float, default: 0.2
+ Length of the bracket.
+ angleA : float, default: 0 degrees
+ Orientation of the bracket, as a counterclockwise angle.
+ 0 degrees means perpendicular to the line.
+ """
+ super().__init__(widthA=widthA, lengthA=lengthA, angleA=angleA)
+
+ @_register_style(_style_list, name="-[")
+ class BracketB(_Curve):
+ """An arrow with an outward square bracket at its end."""
+ arrow = "-["
+
+ def __init__(self, widthB=1., lengthB=0.2, angleB=0):
+ """
+ Parameters
+ ----------
+ widthB : float, default: 1.0
+ Width of the bracket.
+ lengthB : float, default: 0.2
+ Length of the bracket.
+ angleB : float, default: 0 degrees
+ Orientation of the bracket, as a counterclockwise angle.
+ 0 degrees means perpendicular to the line.
+ """
+ super().__init__(widthB=widthB, lengthB=lengthB, angleB=angleB)
+
+ @_register_style(_style_list, name="]-[")
+ class BracketAB(_Curve):
+ """An arrow with outward square brackets at both ends."""
+ arrow = "]-["
+
+ def __init__(self,
+ widthA=1., lengthA=0.2, angleA=0,
+ widthB=1., lengthB=0.2, angleB=0):
+ """
+ Parameters
+ ----------
+ widthA, widthB : float, default: 1.0
+ Width of the bracket.
+ lengthA, lengthB : float, default: 0.2
+ Length of the bracket.
+ angleA, angleB : float, default: 0 degrees
+ Orientation of the bracket, as a counterclockwise angle.
+ 0 degrees means perpendicular to the line.
+ """
+ super().__init__(widthA=widthA, lengthA=lengthA, angleA=angleA,
+ widthB=widthB, lengthB=lengthB, angleB=angleB)
+
+ @_register_style(_style_list, name="|-|")
+ class BarAB(_Curve):
+ """An arrow with vertical bars ``|`` at both ends."""
+ arrow = "|-|"
+
+ def __init__(self, widthA=1., angleA=0, widthB=1., angleB=0):
+ """
+ Parameters
+ ----------
+ widthA, widthB : float, default: 1.0
+ Width of the bracket.
+ angleA, angleB : float, default: 0 degrees
+ Orientation of the bracket, as a counterclockwise angle.
+ 0 degrees means perpendicular to the line.
+ """
+ super().__init__(widthA=widthA, lengthA=0, angleA=angleA,
+ widthB=widthB, lengthB=0, angleB=angleB)
+
+ @_register_style(_style_list, name=']->')
+ class BracketCurve(_Curve):
+ """
+ An arrow with an outward square bracket at its start and a head at
+ the end.
+ """
+ arrow = "]->"
+
+ def __init__(self, widthA=1., lengthA=0.2, angleA=None):
+ """
+ Parameters
+ ----------
+ widthA : float, default: 1.0
+ Width of the bracket.
+ lengthA : float, default: 0.2
+ Length of the bracket.
+ angleA : float, default: 0 degrees
+ Orientation of the bracket, as a counterclockwise angle.
+ 0 degrees means perpendicular to the line.
+ """
+ super().__init__(widthA=widthA, lengthA=lengthA, angleA=angleA)
+
+ @_register_style(_style_list, name='<-[')
+ class CurveBracket(_Curve):
+ """
+ An arrow with an outward square bracket at its end and a head at
+ the start.
+ """
+ arrow = "<-["
+
+ def __init__(self, widthB=1., lengthB=0.2, angleB=None):
+ """
+ Parameters
+ ----------
+ widthB : float, default: 1.0
+ Width of the bracket.
+ lengthB : float, default: 0.2
+ Length of the bracket.
+ angleB : float, default: 0 degrees
+ Orientation of the bracket, as a counterclockwise angle.
+ 0 degrees means perpendicular to the line.
+ """
+ super().__init__(widthB=widthB, lengthB=lengthB, angleB=angleB)
+
+ @_register_style(_style_list)
+ class Simple(_Base):
+ """A simple arrow. Only works with a quadratic Bézier curve."""
+
+ def __init__(self, head_length=.5, head_width=.5, tail_width=.2):
+ """
+ Parameters
+ ----------
+ head_length : float, default: 0.5
+ Length of the arrow head.
+
+ head_width : float, default: 0.5
+ Width of the arrow head.
+
+ tail_width : float, default: 0.2
+ Width of the arrow tail.
+ """
+ self.head_length, self.head_width, self.tail_width = \
+ head_length, head_width, tail_width
+ super().__init__()
+
+ def transmute(self, path, mutation_size, linewidth):
+ # docstring inherited
+ x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path)
+
+ # divide the path into a head and a tail
+ head_length = self.head_length * mutation_size
+ in_f = inside_circle(x2, y2, head_length)
+ arrow_path = [(x0, y0), (x1, y1), (x2, y2)]
+
+ try:
+ arrow_out, arrow_in = \
+ split_bezier_intersecting_with_closedpath(arrow_path, in_f)
+ except NonIntersectingPathException:
+ # if this happens, make a straight line of the head_length
+ # long.
+ x0, y0 = _point_along_a_line(x2, y2, x1, y1, head_length)
+ x1n, y1n = 0.5 * (x0 + x2), 0.5 * (y0 + y2)
+ arrow_in = [(x0, y0), (x1n, y1n), (x2, y2)]
+ arrow_out = None
+
+ # head
+ head_width = self.head_width * mutation_size
+ head_left, head_right = make_wedged_bezier2(arrow_in,
+ head_width / 2., wm=.5)
+
+ # tail
+ if arrow_out is not None:
+ tail_width = self.tail_width * mutation_size
+ tail_left, tail_right = get_parallels(arrow_out,
+ tail_width / 2.)
+
+ patch_path = [(Path.MOVETO, tail_right[0]),
+ (Path.CURVE3, tail_right[1]),
+ (Path.CURVE3, tail_right[2]),
+ (Path.LINETO, head_right[0]),
+ (Path.CURVE3, head_right[1]),
+ (Path.CURVE3, head_right[2]),
+ (Path.CURVE3, head_left[1]),
+ (Path.CURVE3, head_left[0]),
+ (Path.LINETO, tail_left[2]),
+ (Path.CURVE3, tail_left[1]),
+ (Path.CURVE3, tail_left[0]),
+ (Path.LINETO, tail_right[0]),
+ (Path.CLOSEPOLY, tail_right[0]),
+ ]
+ else:
+ patch_path = [(Path.MOVETO, head_right[0]),
+ (Path.CURVE3, head_right[1]),
+ (Path.CURVE3, head_right[2]),
+ (Path.CURVE3, head_left[1]),
+ (Path.CURVE3, head_left[0]),
+ (Path.CLOSEPOLY, head_left[0]),
+ ]
+
+ path = Path([p for c, p in patch_path], [c for c, p in patch_path])
+
+ return path, True
+
+ @_register_style(_style_list)
+ class Fancy(_Base):
+ """A fancy arrow. Only works with a quadratic Bézier curve."""
+
+ def __init__(self, head_length=.4, head_width=.4, tail_width=.4):
+ """
+ Parameters
+ ----------
+ head_length : float, default: 0.4
+ Length of the arrow head.
+
+ head_width : float, default: 0.4
+ Width of the arrow head.
+
+ tail_width : float, default: 0.4
+ Width of the arrow tail.
+ """
+ self.head_length, self.head_width, self.tail_width = \
+ head_length, head_width, tail_width
+ super().__init__()
+
+ def transmute(self, path, mutation_size, linewidth):
+ # docstring inherited
+ x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path)
+
+ # divide the path into a head and a tail
+ head_length = self.head_length * mutation_size
+ arrow_path = [(x0, y0), (x1, y1), (x2, y2)]
+
+ # path for head
+ in_f = inside_circle(x2, y2, head_length)
+ try:
+ path_out, path_in = split_bezier_intersecting_with_closedpath(
+ arrow_path, in_f)
+ except NonIntersectingPathException:
+ # if this happens, make a straight line of the head_length
+ # long.
+ x0, y0 = _point_along_a_line(x2, y2, x1, y1, head_length)
+ x1n, y1n = 0.5 * (x0 + x2), 0.5 * (y0 + y2)
+ arrow_path = [(x0, y0), (x1n, y1n), (x2, y2)]
+ path_head = arrow_path
+ else:
+ path_head = path_in
+
+ # path for head
+ in_f = inside_circle(x2, y2, head_length * .8)
+ path_out, path_in = split_bezier_intersecting_with_closedpath(
+ arrow_path, in_f)
+ path_tail = path_out
+
+ # head
+ head_width = self.head_width * mutation_size
+ head_l, head_r = make_wedged_bezier2(path_head,
+ head_width / 2.,
+ wm=.6)
+
+ # tail
+ tail_width = self.tail_width * mutation_size
+ tail_left, tail_right = make_wedged_bezier2(path_tail,
+ tail_width * .5,
+ w1=1., wm=0.6, w2=0.3)
+
+ # path for head
+ in_f = inside_circle(x0, y0, tail_width * .3)
+ path_in, path_out = split_bezier_intersecting_with_closedpath(
+ arrow_path, in_f)
+ tail_start = path_in[-1]
+
+ head_right, head_left = head_r, head_l
+ patch_path = [(Path.MOVETO, tail_start),
+ (Path.LINETO, tail_right[0]),
+ (Path.CURVE3, tail_right[1]),
+ (Path.CURVE3, tail_right[2]),
+ (Path.LINETO, head_right[0]),
+ (Path.CURVE3, head_right[1]),
+ (Path.CURVE3, head_right[2]),
+ (Path.CURVE3, head_left[1]),
+ (Path.CURVE3, head_left[0]),
+ (Path.LINETO, tail_left[2]),
+ (Path.CURVE3, tail_left[1]),
+ (Path.CURVE3, tail_left[0]),
+ (Path.LINETO, tail_start),
+ (Path.CLOSEPOLY, tail_start),
+ ]
+ path = Path([p for c, p in patch_path], [c for c, p in patch_path])
+
+ return path, True
+
+ @_register_style(_style_list)
+ class Wedge(_Base):
+ """
+ Wedge(?) shape. Only works with a quadratic Bézier curve. The
+ start point has a width of the *tail_width* and the end point has a
+ width of 0. At the middle, the width is *shrink_factor*x*tail_width*.
+ """
+
+ def __init__(self, tail_width=.3, shrink_factor=0.5):
+ """
+ Parameters
+ ----------
+ tail_width : float, default: 0.3
+ Width of the tail.
+
+ shrink_factor : float, default: 0.5
+ Fraction of the arrow width at the middle point.
+ """
+ self.tail_width = tail_width
+ self.shrink_factor = shrink_factor
+ super().__init__()
+
+ def transmute(self, path, mutation_size, linewidth):
+ # docstring inherited
+ x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path)
+
+ arrow_path = [(x0, y0), (x1, y1), (x2, y2)]
+ b_plus, b_minus = make_wedged_bezier2(
+ arrow_path,
+ self.tail_width * mutation_size / 2.,
+ wm=self.shrink_factor)
+
+ patch_path = [(Path.MOVETO, b_plus[0]),
+ (Path.CURVE3, b_plus[1]),
+ (Path.CURVE3, b_plus[2]),
+ (Path.LINETO, b_minus[2]),
+ (Path.CURVE3, b_minus[1]),
+ (Path.CURVE3, b_minus[0]),
+ (Path.CLOSEPOLY, b_minus[0]),
+ ]
+ path = Path([p for c, p in patch_path], [c for c, p in patch_path])
+
+ return path, True
+
+
+class FancyBboxPatch(Patch):
+ """
+ A fancy box around a rectangle with lower left at *xy* = (*x*, *y*)
+ with specified width and height.
+
+ `.FancyBboxPatch` is similar to `.Rectangle`, but it draws a fancy box
+ around the rectangle. The transformation of the rectangle box to the
+ fancy box is delegated to the style classes defined in `.BoxStyle`.
+ """
+
+ _edge_default = True
+
+ def __str__(self):
+ s = self.__class__.__name__ + "((%g, %g), width=%g, height=%g)"
+ return s % (self._x, self._y, self._width, self._height)
+
+ @_docstring.dedent_interpd
+ def __init__(self, xy, width, height, boxstyle="round", *,
+ mutation_scale=1, mutation_aspect=1, **kwargs):
+ """
+ Parameters
+ ----------
+ xy : (float, float)
+ The lower left corner of the box.
+
+ width : float
+ The width of the box.
+
+ height : float
+ The height of the box.
+
+ boxstyle : str or `~matplotlib.patches.BoxStyle`
+ The style of the fancy box. This can either be a `.BoxStyle`
+ instance or a string of the style name and optionally comma
+ separated attributes (e.g. "Round, pad=0.2"). This string is
+ passed to `.BoxStyle` to construct a `.BoxStyle` object. See
+ there for a full documentation.
+
+ The following box styles are available:
+
+ %(BoxStyle:table)s
+
+ mutation_scale : float, default: 1
+ Scaling factor applied to the attributes of the box style
+ (e.g. pad or rounding_size).
+
+ mutation_aspect : float, default: 1
+ The height of the rectangle will be squeezed by this value before
+ the mutation and the mutated box will be stretched by the inverse
+ of it. For example, this allows different horizontal and vertical
+ padding.
+
+ Other Parameters
+ ----------------
+ **kwargs : `~matplotlib.patches.Patch` properties
+
+ %(Patch:kwdoc)s
+ """
+
+ super().__init__(**kwargs)
+ self._x, self._y = xy
+ self._width = width
+ self._height = height
+ self.set_boxstyle(boxstyle)
+ self._mutation_scale = mutation_scale
+ self._mutation_aspect = mutation_aspect
+ self.stale = True
+
+ @_docstring.dedent_interpd
+ def set_boxstyle(self, boxstyle=None, **kwargs):
+ """
+ Set the box style, possibly with further attributes.
+
+ Attributes from the previous box style are not reused.
+
+ Without argument (or with ``boxstyle=None``), the available box styles
+ are returned as a human-readable string.
+
+ Parameters
+ ----------
+ boxstyle : str or `~matplotlib.patches.BoxStyle`
+ The style of the box: either a `.BoxStyle` instance, or a string,
+ which is the style name and optionally comma separated attributes
+ (e.g. "Round,pad=0.2"). Such a string is used to construct a
+ `.BoxStyle` object, as documented in that class.
+
+ The following box styles are available:
+
+ %(BoxStyle:table_and_accepts)s
+
+ **kwargs
+ Additional attributes for the box style. See the table above for
+ supported parameters.
+
+ Examples
+ --------
+ ::
+
+ set_boxstyle("Round,pad=0.2")
+ set_boxstyle("round", pad=0.2)
+ """
+ if boxstyle is None:
+ return BoxStyle.pprint_styles()
+ self._bbox_transmuter = (
+ BoxStyle(boxstyle, **kwargs)
+ if isinstance(boxstyle, str) else boxstyle)
+ self.stale = True
+
+ def get_boxstyle(self):
+ """Return the boxstyle object."""
+ return self._bbox_transmuter
+
+ def set_mutation_scale(self, scale):
+ """
+ Set the mutation scale.
+
+ Parameters
+ ----------
+ scale : float
+ """
+ self._mutation_scale = scale
+ self.stale = True
+
+ def get_mutation_scale(self):
+ """Return the mutation scale."""
+ return self._mutation_scale
+
+ def set_mutation_aspect(self, aspect):
+ """
+ Set the aspect ratio of the bbox mutation.
+
+ Parameters
+ ----------
+ aspect : float
+ """
+ self._mutation_aspect = aspect
+ self.stale = True
+
+ def get_mutation_aspect(self):
+ """Return the aspect ratio of the bbox mutation."""
+ return (self._mutation_aspect if self._mutation_aspect is not None
+ else 1) # backcompat.
+
+ def get_path(self):
+ """Return the mutated path of the rectangle."""
+ boxstyle = self.get_boxstyle()
+ m_aspect = self.get_mutation_aspect()
+ # Call boxstyle with y, height squeezed by aspect_ratio.
+ path = boxstyle(self._x, self._y / m_aspect,
+ self._width, self._height / m_aspect,
+ self.get_mutation_scale())
+ return Path(path.vertices * [1, m_aspect], path.codes) # Unsqueeze y.
+
+ # Following methods are borrowed from the Rectangle class.
+
+ def get_x(self):
+ """Return the left coord of the rectangle."""
+ return self._x
+
+ def get_y(self):
+ """Return the bottom coord of the rectangle."""
+ return self._y
+
+ def get_width(self):
+ """Return the width of the rectangle."""
+ return self._width
+
+ def get_height(self):
+ """Return the height of the rectangle."""
+ return self._height
+
+ def set_x(self, x):
+ """
+ Set the left coord of the rectangle.
+
+ Parameters
+ ----------
+ x : float
+ """
+ self._x = x
+ self.stale = True
+
+ def set_y(self, y):
+ """
+ Set the bottom coord of the rectangle.
+
+ Parameters
+ ----------
+ y : float
+ """
+ self._y = y
+ self.stale = True
+
+ def set_width(self, w):
+ """
+ Set the rectangle width.
+
+ Parameters
+ ----------
+ w : float
+ """
+ self._width = w
+ self.stale = True
+
+ def set_height(self, h):
+ """
+ Set the rectangle height.
+
+ Parameters
+ ----------
+ h : float
+ """
+ self._height = h
+ self.stale = True
+
+ def set_bounds(self, *args):
+ """
+ Set the bounds of the rectangle.
+
+ Call signatures::
+
+ set_bounds(left, bottom, width, height)
+ set_bounds((left, bottom, width, height))
+
+ Parameters
+ ----------
+ left, bottom : float
+ The coordinates of the bottom left corner of the rectangle.
+ width, height : float
+ The width/height of the rectangle.
+ """
+ if len(args) == 1:
+ l, b, w, h = args[0]
+ else:
+ l, b, w, h = args
+ self._x = l
+ self._y = b
+ self._width = w
+ self._height = h
+ self.stale = True
+
+ def get_bbox(self):
+ """Return the `.Bbox`."""
+ return transforms.Bbox.from_bounds(self._x, self._y,
+ self._width, self._height)
+
+
+class FancyArrowPatch(Patch):
+ """
+ A fancy arrow patch.
+
+ It draws an arrow using the `ArrowStyle`. It is primarily used by the
+ `~.axes.Axes.annotate` method. For most purposes, use the annotate method for
+ drawing arrows.
+
+ The head and tail positions are fixed at the specified start and end points
+ of the arrow, but the size and shape (in display coordinates) of the arrow
+ does not change when the axis is moved or zoomed.
+ """
+ _edge_default = True
+
+ def __str__(self):
+ if self._posA_posB is not None:
+ (x1, y1), (x2, y2) = self._posA_posB
+ return f"{type(self).__name__}(({x1:g}, {y1:g})->({x2:g}, {y2:g}))"
+ else:
+ return f"{type(self).__name__}({self._path_original})"
+
+ @_docstring.dedent_interpd
+ @_api.make_keyword_only("3.6", name="path")
+ def __init__(self, posA=None, posB=None, path=None,
+ arrowstyle="simple", connectionstyle="arc3",
+ patchA=None, patchB=None,
+ shrinkA=2, shrinkB=2,
+ mutation_scale=1, mutation_aspect=1,
+ **kwargs):
+ """
+ There are two ways for defining an arrow:
+
+ - If *posA* and *posB* are given, a path connecting two points is
+ created according to *connectionstyle*. The path will be
+ clipped with *patchA* and *patchB* and further shrunken by
+ *shrinkA* and *shrinkB*. An arrow is drawn along this
+ resulting path using the *arrowstyle* parameter.
+
+ - Alternatively if *path* is provided, an arrow is drawn along this
+ path and *patchA*, *patchB*, *shrinkA*, and *shrinkB* are ignored.
+
+ Parameters
+ ----------
+ posA, posB : (float, float), default: None
+ (x, y) coordinates of arrow tail and arrow head respectively.
+
+ path : `~matplotlib.path.Path`, default: None
+ If provided, an arrow is drawn along this path and *patchA*,
+ *patchB*, *shrinkA*, and *shrinkB* are ignored.
+
+ arrowstyle : str or `.ArrowStyle`, default: 'simple'
+ The `.ArrowStyle` with which the fancy arrow is drawn. If a
+ string, it should be one of the available arrowstyle names, with
+ optional comma-separated attributes. The optional attributes are
+ meant to be scaled with the *mutation_scale*. The following arrow
+ styles are available:
+
+ %(ArrowStyle:table)s
+
+ connectionstyle : str or `.ConnectionStyle` or None, optional, \
+default: 'arc3'
+ The `.ConnectionStyle` with which *posA* and *posB* are connected.
+ If a string, it should be one of the available connectionstyle
+ names, with optional comma-separated attributes. The following
+ connection styles are available:
+
+ %(ConnectionStyle:table)s
+
+ patchA, patchB : `~matplotlib.patches.Patch`, default: None
+ Head and tail patches, respectively.
+
+ shrinkA, shrinkB : float, default: 2
+ Shrinking factor of the tail and head of the arrow respectively.
+
+ mutation_scale : float, default: 1
+ Value with which attributes of *arrowstyle* (e.g., *head_length*)
+ will be scaled.
+
+ mutation_aspect : None or float, default: None
+ The height of the rectangle will be squeezed by this value before
+ the mutation and the mutated box will be stretched by the inverse
+ of it.
+
+ Other Parameters
+ ----------------
+ **kwargs : `~matplotlib.patches.Patch` properties, optional
+ Here is a list of available `.Patch` properties:
+
+ %(Patch:kwdoc)s
+
+ In contrast to other patches, the default ``capstyle`` and
+ ``joinstyle`` for `FancyArrowPatch` are set to ``"round"``.
+ """
+ # Traditionally, the cap- and joinstyle for FancyArrowPatch are round
+ kwargs.setdefault("joinstyle", JoinStyle.round)
+ kwargs.setdefault("capstyle", CapStyle.round)
+
+ super().__init__(**kwargs)
+
+ if posA is not None and posB is not None and path is None:
+ self._posA_posB = [posA, posB]
+
+ if connectionstyle is None:
+ connectionstyle = "arc3"
+ self.set_connectionstyle(connectionstyle)
+
+ elif posA is None and posB is None and path is not None:
+ self._posA_posB = None
+ else:
+ raise ValueError("Either posA and posB, or path need to provided")
+
+ self.patchA = patchA
+ self.patchB = patchB
+ self.shrinkA = shrinkA
+ self.shrinkB = shrinkB
+
+ self._path_original = path
+
+ self.set_arrowstyle(arrowstyle)
+
+ self._mutation_scale = mutation_scale
+ self._mutation_aspect = mutation_aspect
+
+ self._dpi_cor = 1.0
+
+ def set_positions(self, posA, posB):
+ """
+ Set the start and end positions of the connecting path.
+
+ Parameters
+ ----------
+ posA, posB : None, tuple
+ (x, y) coordinates of arrow tail and arrow head respectively. If
+ `None` use current value.
+ """
+ if posA is not None:
+ self._posA_posB[0] = posA
+ if posB is not None:
+ self._posA_posB[1] = posB
+ self.stale = True
+
+ def set_patchA(self, patchA):
+ """
+ Set the tail patch.
+
+ Parameters
+ ----------
+ patchA : `.patches.Patch`
+ """
+ self.patchA = patchA
+ self.stale = True
+
+ def set_patchB(self, patchB):
+ """
+ Set the head patch.
+
+ Parameters
+ ----------
+ patchB : `.patches.Patch`
+ """
+ self.patchB = patchB
+ self.stale = True
+
+ @_docstring.dedent_interpd
+ def set_connectionstyle(self, connectionstyle=None, **kwargs):
+ """
+ Set the connection style, possibly with further attributes.
+
+ Attributes from the previous connection style are not reused.
+
+ Without argument (or with ``connectionstyle=None``), the available box
+ styles are returned as a human-readable string.
+
+ Parameters
+ ----------
+ connectionstyle : str or `~matplotlib.patches.ConnectionStyle`
+ The style of the connection: either a `.ConnectionStyle` instance,
+ or a string, which is the style name and optionally comma separated
+ attributes (e.g. "Arc,armA=30,rad=10"). Such a string is used to
+ construct a `.ConnectionStyle` object, as documented in that class.
+
+ The following connection styles are available:
+
+ %(ConnectionStyle:table_and_accepts)s
+
+ **kwargs
+ Additional attributes for the connection style. See the table above
+ for supported parameters.
+
+ Examples
+ --------
+ ::
+
+ set_connectionstyle("Arc,armA=30,rad=10")
+ set_connectionstyle("arc", armA=30, rad=10)
+ """
+ if connectionstyle is None:
+ return ConnectionStyle.pprint_styles()
+ self._connector = (
+ ConnectionStyle(connectionstyle, **kwargs)
+ if isinstance(connectionstyle, str) else connectionstyle)
+ self.stale = True
+
+ def get_connectionstyle(self):
+ """Return the `ConnectionStyle` used."""
+ return self._connector
+
+ def set_arrowstyle(self, arrowstyle=None, **kwargs):
+ """
+ Set the arrow style, possibly with further attributes.
+
+ Attributes from the previous arrow style are not reused.
+
+ Without argument (or with ``arrowstyle=None``), the available box
+ styles are returned as a human-readable string.
+
+ Parameters
+ ----------
+ arrowstyle : str or `~matplotlib.patches.ArrowStyle`
+ The style of the arrow: either a `.ArrowStyle` instance, or a
+ string, which is the style name and optionally comma separated
+ attributes (e.g. "Fancy,head_length=0.2"). Such a string is used to
+ construct a `.ArrowStyle` object, as documented in that class.
+
+ The following arrow styles are available:
+
+ %(ArrowStyle:table_and_accepts)s
+
+ **kwargs
+ Additional attributes for the arrow style. See the table above for
+ supported parameters.
+
+ Examples
+ --------
+ ::
+
+ set_arrowstyle("Fancy,head_length=0.2")
+ set_arrowstyle("fancy", head_length=0.2)
+ """
+ if arrowstyle is None:
+ return ArrowStyle.pprint_styles()
+ self._arrow_transmuter = (
+ ArrowStyle(arrowstyle, **kwargs)
+ if isinstance(arrowstyle, str) else arrowstyle)
+ self.stale = True
+
+ def get_arrowstyle(self):
+ """Return the arrowstyle object."""
+ return self._arrow_transmuter
+
+ def set_mutation_scale(self, scale):
+ """
+ Set the mutation scale.
+
+ Parameters
+ ----------
+ scale : float
+ """
+ self._mutation_scale = scale
+ self.stale = True
+
+ def get_mutation_scale(self):
+ """
+ Return the mutation scale.
+
+ Returns
+ -------
+ scalar
+ """
+ return self._mutation_scale
+
+ def set_mutation_aspect(self, aspect):
+ """
+ Set the aspect ratio of the bbox mutation.
+
+ Parameters
+ ----------
+ aspect : float
+ """
+ self._mutation_aspect = aspect
+ self.stale = True
+
+ def get_mutation_aspect(self):
+ """Return the aspect ratio of the bbox mutation."""
+ return (self._mutation_aspect if self._mutation_aspect is not None
+ else 1) # backcompat.
+
+ def get_path(self):
+ """Return the path of the arrow in the data coordinates."""
+ # The path is generated in display coordinates, then converted back to
+ # data coordinates.
+ _path, fillable = self._get_path_in_displaycoord()
+ if np.iterable(fillable):
+ _path = Path.make_compound_path(*_path)
+ return self.get_transform().inverted().transform_path(_path)
+
+ def _get_path_in_displaycoord(self):
+ """Return the mutated path of the arrow in display coordinates."""
+ dpi_cor = self._dpi_cor
+
+ if self._posA_posB is not None:
+ posA = self._convert_xy_units(self._posA_posB[0])
+ posB = self._convert_xy_units(self._posA_posB[1])
+ (posA, posB) = self.get_transform().transform((posA, posB))
+ _path = self.get_connectionstyle()(posA, posB,
+ patchA=self.patchA,
+ patchB=self.patchB,
+ shrinkA=self.shrinkA * dpi_cor,
+ shrinkB=self.shrinkB * dpi_cor
+ )
+ else:
+ _path = self.get_transform().transform_path(self._path_original)
+
+ _path, fillable = self.get_arrowstyle()(
+ _path,
+ self.get_mutation_scale() * dpi_cor,
+ self.get_linewidth() * dpi_cor,
+ self.get_mutation_aspect())
+
+ return _path, fillable
+
+ def draw(self, renderer):
+ if not self.get_visible():
+ return
+
+ # FIXME: dpi_cor is for the dpi-dependency of the linewidth. There
+ # could be room for improvement. Maybe _get_path_in_displaycoord could
+ # take a renderer argument, but get_path should be adapted too.
+ self._dpi_cor = renderer.points_to_pixels(1.)
+ path, fillable = self._get_path_in_displaycoord()
+
+ if not np.iterable(fillable):
+ path = [path]
+ fillable = [fillable]
+
+ affine = transforms.IdentityTransform()
+
+ self._draw_paths_with_artist_properties(
+ renderer,
+ [(p, affine, self._facecolor if f and self._facecolor[3] else None)
+ for p, f in zip(path, fillable)])
+
+
+class ConnectionPatch(FancyArrowPatch):
+ """A patch that connects two points (possibly in different axes)."""
+
+ def __str__(self):
+ return "ConnectionPatch((%g, %g), (%g, %g))" % \
+ (self.xy1[0], self.xy1[1], self.xy2[0], self.xy2[1])
+
+ @_docstring.dedent_interpd
+ @_api.make_keyword_only("3.6", name="axesA")
+ def __init__(self, xyA, xyB, coordsA, coordsB=None,
+ axesA=None, axesB=None,
+ arrowstyle="-",
+ connectionstyle="arc3",
+ patchA=None,
+ patchB=None,
+ shrinkA=0.,
+ shrinkB=0.,
+ mutation_scale=10.,
+ mutation_aspect=None,
+ clip_on=False,
+ **kwargs):
+ """
+ Connect point *xyA* in *coordsA* with point *xyB* in *coordsB*.
+
+ Valid keys are
+
+ =============== ======================================================
+ Key Description
+ =============== ======================================================
+ arrowstyle the arrow style
+ connectionstyle the connection style
+ relpos default is (0.5, 0.5)
+ patchA default is bounding box of the text
+ patchB default is None
+ shrinkA default is 2 points
+ shrinkB default is 2 points
+ mutation_scale default is text size (in points)
+ mutation_aspect default is 1.
+ ? any key for `matplotlib.patches.PathPatch`
+ =============== ======================================================
+
+ *coordsA* and *coordsB* are strings that indicate the
+ coordinates of *xyA* and *xyB*.
+
+ ==================== ==================================================
+ Property Description
+ ==================== ==================================================
+ 'figure points' points from the lower left corner of the figure
+ 'figure pixels' pixels from the lower left corner of the figure
+ 'figure fraction' 0, 0 is lower left of figure and 1, 1 is upper
+ right
+ 'subfigure points' points from the lower left corner of the subfigure
+ 'subfigure pixels' pixels from the lower left corner of the subfigure
+ 'subfigure fraction' fraction of the subfigure, 0, 0 is lower left.
+ 'axes points' points from lower left corner of axes
+ 'axes pixels' pixels from lower left corner of axes
+ 'axes fraction' 0, 0 is lower left of axes and 1, 1 is upper right
+ 'data' use the coordinate system of the object being
+ annotated (default)
+ 'offset points' offset (in points) from the *xy* value
+ 'polar' you can specify *theta*, *r* for the annotation,
+ even in cartesian plots. Note that if you are
+ using a polar axes, you do not need to specify
+ polar for the coordinate system since that is the
+ native "data" coordinate system.
+ ==================== ==================================================
+
+ Alternatively they can be set to any valid
+ `~matplotlib.transforms.Transform`.
+
+ Note that 'subfigure pixels' and 'figure pixels' are the same
+ for the parent figure, so users who want code that is usable in
+ a subfigure can use 'subfigure pixels'.
+
+ .. note::
+
+ Using `ConnectionPatch` across two `~.axes.Axes` instances
+ is not directly compatible with :doc:`constrained layout
+ `. Add the artist
+ directly to the `.Figure` instead of adding it to a specific Axes,
+ or exclude it from the layout using ``con.set_in_layout(False)``.
+
+ .. code-block:: default
+
+ fig, ax = plt.subplots(1, 2, constrained_layout=True)
+ con = ConnectionPatch(..., axesA=ax[0], axesB=ax[1])
+ fig.add_artist(con)
+
+ """
+ if coordsB is None:
+ coordsB = coordsA
+ # we'll draw ourself after the artist we annotate by default
+ self.xy1 = xyA
+ self.xy2 = xyB
+ self.coords1 = coordsA
+ self.coords2 = coordsB
+
+ self.axesA = axesA
+ self.axesB = axesB
+
+ super().__init__(posA=(0, 0), posB=(1, 1),
+ arrowstyle=arrowstyle,
+ connectionstyle=connectionstyle,
+ patchA=patchA, patchB=patchB,
+ shrinkA=shrinkA, shrinkB=shrinkB,
+ mutation_scale=mutation_scale,
+ mutation_aspect=mutation_aspect,
+ clip_on=clip_on,
+ **kwargs)
+ # if True, draw annotation only if self.xy is inside the axes
+ self._annotation_clip = None
+
+ def _get_xy(self, xy, s, axes=None):
+ """Calculate the pixel position of given point."""
+ s0 = s # For the error message, if needed.
+ if axes is None:
+ axes = self.axes
+ xy = np.array(xy)
+ if s in ["figure points", "axes points"]:
+ xy *= self.figure.dpi / 72
+ s = s.replace("points", "pixels")
+ elif s == "figure fraction":
+ s = self.figure.transFigure
+ elif s == "subfigure fraction":
+ s = self.figure.transSubfigure
+ elif s == "axes fraction":
+ s = axes.transAxes
+ x, y = xy
+
+ if s == 'data':
+ trans = axes.transData
+ x = float(self.convert_xunits(x))
+ y = float(self.convert_yunits(y))
+ return trans.transform((x, y))
+ elif s == 'offset points':
+ if self.xycoords == 'offset points': # prevent recursion
+ return self._get_xy(self.xy, 'data')
+ return (
+ self._get_xy(self.xy, self.xycoords) # converted data point
+ + xy * self.figure.dpi / 72) # converted offset
+ elif s == 'polar':
+ theta, r = x, y
+ x = r * np.cos(theta)
+ y = r * np.sin(theta)
+ trans = axes.transData
+ return trans.transform((x, y))
+ elif s == 'figure pixels':
+ # pixels from the lower left corner of the figure
+ bb = self.figure.figbbox
+ x = bb.x0 + x if x >= 0 else bb.x1 + x
+ y = bb.y0 + y if y >= 0 else bb.y1 + y
+ return x, y
+ elif s == 'subfigure pixels':
+ # pixels from the lower left corner of the figure
+ bb = self.figure.bbox
+ x = bb.x0 + x if x >= 0 else bb.x1 + x
+ y = bb.y0 + y if y >= 0 else bb.y1 + y
+ return x, y
+ elif s == 'axes pixels':
+ # pixels from the lower left corner of the axes
+ bb = axes.bbox
+ x = bb.x0 + x if x >= 0 else bb.x1 + x
+ y = bb.y0 + y if y >= 0 else bb.y1 + y
+ return x, y
+ elif isinstance(s, transforms.Transform):
+ return s.transform(xy)
+ else:
+ raise ValueError(f"{s0} is not a valid coordinate transformation")
+
+ def set_annotation_clip(self, b):
+ """
+ Set the annotation's clipping behavior.
+
+ Parameters
+ ----------
+ b : bool or None
+ - True: The annotation will be clipped when ``self.xy`` is
+ outside the axes.
+ - False: The annotation will always be drawn.
+ - None: The annotation will be clipped when ``self.xy`` is
+ outside the axes and ``self.xycoords == "data"``.
+ """
+ self._annotation_clip = b
+ self.stale = True
+
+ def get_annotation_clip(self):
+ """
+ Return the clipping behavior.
+
+ See `.set_annotation_clip` for the meaning of the return value.
+ """
+ return self._annotation_clip
+
+ def _get_path_in_displaycoord(self):
+ """Return the mutated path of the arrow in display coordinates."""
+ dpi_cor = self._dpi_cor
+ posA = self._get_xy(self.xy1, self.coords1, self.axesA)
+ posB = self._get_xy(self.xy2, self.coords2, self.axesB)
+ path = self.get_connectionstyle()(
+ posA, posB,
+ patchA=self.patchA, patchB=self.patchB,
+ shrinkA=self.shrinkA * dpi_cor, shrinkB=self.shrinkB * dpi_cor,
+ )
+ path, fillable = self.get_arrowstyle()(
+ path,
+ self.get_mutation_scale() * dpi_cor,
+ self.get_linewidth() * dpi_cor,
+ self.get_mutation_aspect()
+ )
+ return path, fillable
+
+ def _check_xy(self, renderer):
+ """Check whether the annotation needs to be drawn."""
+
+ b = self.get_annotation_clip()
+
+ if b or (b is None and self.coords1 == "data"):
+ xy_pixel = self._get_xy(self.xy1, self.coords1, self.axesA)
+ if self.axesA is None:
+ axes = self.axes
+ else:
+ axes = self.axesA
+ if not axes.contains_point(xy_pixel):
+ return False
+
+ if b or (b is None and self.coords2 == "data"):
+ xy_pixel = self._get_xy(self.xy2, self.coords2, self.axesB)
+ if self.axesB is None:
+ axes = self.axes
+ else:
+ axes = self.axesB
+ if not axes.contains_point(xy_pixel):
+ return False
+
+ return True
+
+ def draw(self, renderer):
+ if renderer is not None:
+ self._renderer = renderer
+ if not self.get_visible() or not self._check_xy(renderer):
+ return
+ super().draw(renderer)
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/path.py b/omnilmm/lib/python3.10/site-packages/matplotlib/path.py
new file mode 100644
index 0000000000000000000000000000000000000000..4856c7444c6341a99d6fd72c933f34f9c7a9e6d5
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/path.py
@@ -0,0 +1,1083 @@
+r"""
+A module for dealing with the polylines used throughout Matplotlib.
+
+The primary class for polyline handling in Matplotlib is `Path`. Almost all
+vector drawing makes use of `Path`\s somewhere in the drawing pipeline.
+
+Whilst a `Path` instance itself cannot be drawn, some `.Artist` subclasses,
+such as `.PathPatch` and `.PathCollection`, can be used for convenient `Path`
+visualisation.
+"""
+
+import copy
+from functools import lru_cache
+from weakref import WeakValueDictionary
+
+import numpy as np
+
+import matplotlib as mpl
+from . import _api, _path
+from .cbook import _to_unmasked_float_array, simple_linear_interpolation
+from .bezier import BezierSegment
+
+
+class Path:
+ """
+ A series of possibly disconnected, possibly closed, line and curve
+ segments.
+
+ The underlying storage is made up of two parallel numpy arrays:
+
+ - *vertices*: an Nx2 float array of vertices
+ - *codes*: an N-length uint8 array of path codes, or None
+
+ These two arrays always have the same length in the first
+ dimension. For example, to represent a cubic curve, you must
+ provide three vertices and three ``CURVE4`` codes.
+
+ The code types are:
+
+ - ``STOP`` : 1 vertex (ignored)
+ A marker for the end of the entire path (currently not required and
+ ignored)
+
+ - ``MOVETO`` : 1 vertex
+ Pick up the pen and move to the given vertex.
+
+ - ``LINETO`` : 1 vertex
+ Draw a line from the current position to the given vertex.
+
+ - ``CURVE3`` : 1 control point, 1 endpoint
+ Draw a quadratic Bézier curve from the current position, with the given
+ control point, to the given end point.
+
+ - ``CURVE4`` : 2 control points, 1 endpoint
+ Draw a cubic Bézier curve from the current position, with the given
+ control points, to the given end point.
+
+ - ``CLOSEPOLY`` : 1 vertex (ignored)
+ Draw a line segment to the start point of the current polyline.
+
+ If *codes* is None, it is interpreted as a ``MOVETO`` followed by a series
+ of ``LINETO``.
+
+ Users of Path objects should not access the vertices and codes arrays
+ directly. Instead, they should use `iter_segments` or `cleaned` to get the
+ vertex/code pairs. This helps, in particular, to consistently handle the
+ case of *codes* being None.
+
+ Some behavior of Path objects can be controlled by rcParams. See the
+ rcParams whose keys start with 'path.'.
+
+ .. note::
+
+ The vertices and codes arrays should be treated as
+ immutable -- there are a number of optimizations and assumptions
+ made up front in the constructor that will not change when the
+ data changes.
+ """
+
+ code_type = np.uint8
+
+ # Path codes
+ STOP = code_type(0) # 1 vertex
+ MOVETO = code_type(1) # 1 vertex
+ LINETO = code_type(2) # 1 vertex
+ CURVE3 = code_type(3) # 2 vertices
+ CURVE4 = code_type(4) # 3 vertices
+ CLOSEPOLY = code_type(79) # 1 vertex
+
+ #: A dictionary mapping Path codes to the number of vertices that the
+ #: code expects.
+ NUM_VERTICES_FOR_CODE = {STOP: 1,
+ MOVETO: 1,
+ LINETO: 1,
+ CURVE3: 2,
+ CURVE4: 3,
+ CLOSEPOLY: 1}
+
+ def __init__(self, vertices, codes=None, _interpolation_steps=1,
+ closed=False, readonly=False):
+ """
+ Create a new path with the given vertices and codes.
+
+ Parameters
+ ----------
+ vertices : (N, 2) array-like
+ The path vertices, as an array, masked array or sequence of pairs.
+ Masked values, if any, will be converted to NaNs, which are then
+ handled correctly by the Agg PathIterator and other consumers of
+ path data, such as :meth:`iter_segments`.
+ codes : array-like or None, optional
+ N-length array of integers representing the codes of the path.
+ If not None, codes must be the same length as vertices.
+ If None, *vertices* will be treated as a series of line segments.
+ _interpolation_steps : int, optional
+ Used as a hint to certain projections, such as Polar, that this
+ path should be linearly interpolated immediately before drawing.
+ This attribute is primarily an implementation detail and is not
+ intended for public use.
+ closed : bool, optional
+ If *codes* is None and closed is True, vertices will be treated as
+ line segments of a closed polygon. Note that the last vertex will
+ then be ignored (as the corresponding code will be set to
+ CLOSEPOLY).
+ readonly : bool, optional
+ Makes the path behave in an immutable way and sets the vertices
+ and codes as read-only arrays.
+ """
+ vertices = _to_unmasked_float_array(vertices)
+ _api.check_shape((None, 2), vertices=vertices)
+
+ if codes is not None:
+ codes = np.asarray(codes, self.code_type)
+ if codes.ndim != 1 or len(codes) != len(vertices):
+ raise ValueError("'codes' must be a 1D list or array with the "
+ "same length of 'vertices'. "
+ f"Your vertices have shape {vertices.shape} "
+ f"but your codes have shape {codes.shape}")
+ if len(codes) and codes[0] != self.MOVETO:
+ raise ValueError("The first element of 'code' must be equal "
+ f"to 'MOVETO' ({self.MOVETO}). "
+ f"Your first code is {codes[0]}")
+ elif closed and len(vertices):
+ codes = np.empty(len(vertices), dtype=self.code_type)
+ codes[0] = self.MOVETO
+ codes[1:-1] = self.LINETO
+ codes[-1] = self.CLOSEPOLY
+
+ self._vertices = vertices
+ self._codes = codes
+ self._interpolation_steps = _interpolation_steps
+ self._update_values()
+
+ if readonly:
+ self._vertices.flags.writeable = False
+ if self._codes is not None:
+ self._codes.flags.writeable = False
+ self._readonly = True
+ else:
+ self._readonly = False
+
+ @classmethod
+ def _fast_from_codes_and_verts(cls, verts, codes, internals_from=None):
+ """
+ Create a Path instance without the expense of calling the constructor.
+
+ Parameters
+ ----------
+ verts : numpy array
+ codes : numpy array
+ internals_from : Path or None
+ If not None, another `Path` from which the attributes
+ ``should_simplify``, ``simplify_threshold``, and
+ ``interpolation_steps`` will be copied. Note that ``readonly`` is
+ never copied, and always set to ``False`` by this constructor.
+ """
+ pth = cls.__new__(cls)
+ pth._vertices = _to_unmasked_float_array(verts)
+ pth._codes = codes
+ pth._readonly = False
+ if internals_from is not None:
+ pth._should_simplify = internals_from._should_simplify
+ pth._simplify_threshold = internals_from._simplify_threshold
+ pth._interpolation_steps = internals_from._interpolation_steps
+ else:
+ pth._should_simplify = True
+ pth._simplify_threshold = mpl.rcParams['path.simplify_threshold']
+ pth._interpolation_steps = 1
+ return pth
+
+ @classmethod
+ def _create_closed(cls, vertices):
+ """
+ Create a closed polygonal path going through *vertices*.
+
+ Unlike ``Path(..., closed=True)``, *vertices* should **not** end with
+ an entry for the CLOSEPATH; this entry is added by `._create_closed`.
+ """
+ v = _to_unmasked_float_array(vertices)
+ return cls(np.concatenate([v, v[:1]]), closed=True)
+
+ def _update_values(self):
+ self._simplify_threshold = mpl.rcParams['path.simplify_threshold']
+ self._should_simplify = (
+ self._simplify_threshold > 0 and
+ mpl.rcParams['path.simplify'] and
+ len(self._vertices) >= 128 and
+ (self._codes is None or np.all(self._codes <= Path.LINETO))
+ )
+
+ @property
+ def vertices(self):
+ """
+ The list of vertices in the `Path` as an Nx2 numpy array.
+ """
+ return self._vertices
+
+ @vertices.setter
+ def vertices(self, vertices):
+ if self._readonly:
+ raise AttributeError("Can't set vertices on a readonly Path")
+ self._vertices = vertices
+ self._update_values()
+
+ @property
+ def codes(self):
+ """
+ The list of codes in the `Path` as a 1D numpy array. Each
+ code is one of `STOP`, `MOVETO`, `LINETO`, `CURVE3`, `CURVE4`
+ or `CLOSEPOLY`. For codes that correspond to more than one
+ vertex (`CURVE3` and `CURVE4`), that code will be repeated so
+ that the length of `vertices` and `codes` is always
+ the same.
+ """
+ return self._codes
+
+ @codes.setter
+ def codes(self, codes):
+ if self._readonly:
+ raise AttributeError("Can't set codes on a readonly Path")
+ self._codes = codes
+ self._update_values()
+
+ @property
+ def simplify_threshold(self):
+ """
+ The fraction of a pixel difference below which vertices will
+ be simplified out.
+ """
+ return self._simplify_threshold
+
+ @simplify_threshold.setter
+ def simplify_threshold(self, threshold):
+ self._simplify_threshold = threshold
+
+ @property
+ def should_simplify(self):
+ """
+ `True` if the vertices array should be simplified.
+ """
+ return self._should_simplify
+
+ @should_simplify.setter
+ def should_simplify(self, should_simplify):
+ self._should_simplify = should_simplify
+
+ @property
+ def readonly(self):
+ """
+ `True` if the `Path` is read-only.
+ """
+ return self._readonly
+
+ def copy(self):
+ """
+ Return a shallow copy of the `Path`, which will share the
+ vertices and codes with the source `Path`.
+ """
+ return copy.copy(self)
+
+ def __deepcopy__(self, memo=None):
+ """
+ Return a deepcopy of the `Path`. The `Path` will not be
+ readonly, even if the source `Path` is.
+ """
+ # Deepcopying arrays (vertices, codes) strips the writeable=False flag.
+ p = copy.deepcopy(super(), memo)
+ p._readonly = False
+ return p
+
+ deepcopy = __deepcopy__
+
+ @classmethod
+ def make_compound_path_from_polys(cls, XY):
+ """
+ Make a compound `Path` object to draw a number of polygons with equal
+ numbers of sides.
+
+ .. plot:: gallery/misc/histogram_path.py
+
+ Parameters
+ ----------
+ XY : (numpolys, numsides, 2) array
+ """
+ # for each poly: 1 for the MOVETO, (numsides-1) for the LINETO, 1 for
+ # the CLOSEPOLY; the vert for the closepoly is ignored but we still
+ # need it to keep the codes aligned with the vertices
+ numpolys, numsides, two = XY.shape
+ if two != 2:
+ raise ValueError("The third dimension of 'XY' must be 2")
+ stride = numsides + 1
+ nverts = numpolys * stride
+ verts = np.zeros((nverts, 2))
+ codes = np.full(nverts, cls.LINETO, dtype=cls.code_type)
+ codes[0::stride] = cls.MOVETO
+ codes[numsides::stride] = cls.CLOSEPOLY
+ for i in range(numsides):
+ verts[i::stride] = XY[:, i]
+ return cls(verts, codes)
+
+ @classmethod
+ def make_compound_path(cls, *args):
+ """
+ Make a compound path from a list of `Path` objects. Blindly removes
+ all `Path.STOP` control points.
+ """
+ # Handle an empty list in args (i.e. no args).
+ if not args:
+ return Path(np.empty([0, 2], dtype=np.float32))
+ vertices = np.concatenate([x.vertices for x in args])
+ codes = np.empty(len(vertices), dtype=cls.code_type)
+ i = 0
+ for path in args:
+ if path.codes is None:
+ codes[i] = cls.MOVETO
+ codes[i + 1:i + len(path.vertices)] = cls.LINETO
+ else:
+ codes[i:i + len(path.codes)] = path.codes
+ i += len(path.vertices)
+ # remove STOP's, since internal STOPs are a bug
+ not_stop_mask = codes != cls.STOP
+ vertices = vertices[not_stop_mask, :]
+ codes = codes[not_stop_mask]
+
+ return cls(vertices, codes)
+
+ def __repr__(self):
+ return "Path(%r, %r)" % (self.vertices, self.codes)
+
+ def __len__(self):
+ return len(self.vertices)
+
+ def iter_segments(self, transform=None, remove_nans=True, clip=None,
+ snap=False, stroke_width=1.0, simplify=None,
+ curves=True, sketch=None):
+ """
+ Iterate over all curve segments in the path.
+
+ Each iteration returns a pair ``(vertices, code)``, where ``vertices``
+ is a sequence of 1-3 coordinate pairs, and ``code`` is a `Path` code.
+
+ Additionally, this method can provide a number of standard cleanups and
+ conversions to the path.
+
+ Parameters
+ ----------
+ transform : None or :class:`~matplotlib.transforms.Transform`
+ If not None, the given affine transformation will be applied to the
+ path.
+ remove_nans : bool, optional
+ Whether to remove all NaNs from the path and skip over them using
+ MOVETO commands.
+ clip : None or (float, float, float, float), optional
+ If not None, must be a four-tuple (x1, y1, x2, y2)
+ defining a rectangle in which to clip the path.
+ snap : None or bool, optional
+ If True, snap all nodes to pixels; if False, don't snap them.
+ If None, snap if the path contains only segments
+ parallel to the x or y axes, and no more than 1024 of them.
+ stroke_width : float, optional
+ The width of the stroke being drawn (used for path snapping).
+ simplify : None or bool, optional
+ Whether to simplify the path by removing vertices
+ that do not affect its appearance. If None, use the
+ :attr:`should_simplify` attribute. See also :rc:`path.simplify`
+ and :rc:`path.simplify_threshold`.
+ curves : bool, optional
+ If True, curve segments will be returned as curve segments.
+ If False, all curves will be converted to line segments.
+ sketch : None or sequence, optional
+ If not None, must be a 3-tuple of the form
+ (scale, length, randomness), representing the sketch parameters.
+ """
+ if not len(self):
+ return
+
+ cleaned = self.cleaned(transform=transform,
+ remove_nans=remove_nans, clip=clip,
+ snap=snap, stroke_width=stroke_width,
+ simplify=simplify, curves=curves,
+ sketch=sketch)
+
+ # Cache these object lookups for performance in the loop.
+ NUM_VERTICES_FOR_CODE = self.NUM_VERTICES_FOR_CODE
+ STOP = self.STOP
+
+ vertices = iter(cleaned.vertices)
+ codes = iter(cleaned.codes)
+ for curr_vertices, code in zip(vertices, codes):
+ if code == STOP:
+ break
+ extra_vertices = NUM_VERTICES_FOR_CODE[code] - 1
+ if extra_vertices:
+ for i in range(extra_vertices):
+ next(codes)
+ curr_vertices = np.append(curr_vertices, next(vertices))
+ yield curr_vertices, code
+
+ def iter_bezier(self, **kwargs):
+ """
+ Iterate over each Bézier curve (lines included) in a Path.
+
+ Parameters
+ ----------
+ **kwargs
+ Forwarded to `.iter_segments`.
+
+ Yields
+ ------
+ B : matplotlib.bezier.BezierSegment
+ The Bézier curves that make up the current path. Note in particular
+ that freestanding points are Bézier curves of order 0, and lines
+ are Bézier curves of order 1 (with two control points).
+ code : Path.code_type
+ The code describing what kind of curve is being returned.
+ Path.MOVETO, Path.LINETO, Path.CURVE3, Path.CURVE4 correspond to
+ Bézier curves with 1, 2, 3, and 4 control points (respectively).
+ Path.CLOSEPOLY is a Path.LINETO with the control points correctly
+ chosen based on the start/end points of the current stroke.
+ """
+ first_vert = None
+ prev_vert = None
+ for verts, code in self.iter_segments(**kwargs):
+ if first_vert is None:
+ if code != Path.MOVETO:
+ raise ValueError("Malformed path, must start with MOVETO.")
+ if code == Path.MOVETO: # a point is like "CURVE1"
+ first_vert = verts
+ yield BezierSegment(np.array([first_vert])), code
+ elif code == Path.LINETO: # "CURVE2"
+ yield BezierSegment(np.array([prev_vert, verts])), code
+ elif code == Path.CURVE3:
+ yield BezierSegment(np.array([prev_vert, verts[:2],
+ verts[2:]])), code
+ elif code == Path.CURVE4:
+ yield BezierSegment(np.array([prev_vert, verts[:2],
+ verts[2:4], verts[4:]])), code
+ elif code == Path.CLOSEPOLY:
+ yield BezierSegment(np.array([prev_vert, first_vert])), code
+ elif code == Path.STOP:
+ return
+ else:
+ raise ValueError(f"Invalid Path.code_type: {code}")
+ prev_vert = verts[-2:]
+
+ def cleaned(self, transform=None, remove_nans=False, clip=None,
+ *, simplify=False, curves=False,
+ stroke_width=1.0, snap=False, sketch=None):
+ """
+ Return a new Path with vertices and codes cleaned according to the
+ parameters.
+
+ See Also
+ --------
+ Path.iter_segments : for details of the keyword arguments.
+ """
+ vertices, codes = _path.cleanup_path(
+ self, transform, remove_nans, clip, snap, stroke_width, simplify,
+ curves, sketch)
+ pth = Path._fast_from_codes_and_verts(vertices, codes, self)
+ if not simplify:
+ pth._should_simplify = False
+ return pth
+
+ def transformed(self, transform):
+ """
+ Return a transformed copy of the path.
+
+ See Also
+ --------
+ matplotlib.transforms.TransformedPath
+ A specialized path class that will cache the transformed result and
+ automatically update when the transform changes.
+ """
+ return Path(transform.transform(self.vertices), self.codes,
+ self._interpolation_steps)
+
+ def contains_point(self, point, transform=None, radius=0.0):
+ """
+ Return whether the area enclosed by the path contains the given point.
+
+ The path is always treated as closed; i.e. if the last code is not
+ CLOSEPOLY an implicit segment connecting the last vertex to the first
+ vertex is assumed.
+
+ Parameters
+ ----------
+ point : (float, float)
+ The point (x, y) to check.
+ transform : `matplotlib.transforms.Transform`, optional
+ If not ``None``, *point* will be compared to ``self`` transformed
+ by *transform*; i.e. for a correct check, *transform* should
+ transform the path into the coordinate system of *point*.
+ radius : float, default: 0
+ Additional margin on the path in coordinates of *point*.
+ The path is extended tangentially by *radius/2*; i.e. if you would
+ draw the path with a linewidth of *radius*, all points on the line
+ would still be considered to be contained in the area. Conversely,
+ negative values shrink the area: Points on the imaginary line
+ will be considered outside the area.
+
+ Returns
+ -------
+ bool
+
+ Notes
+ -----
+ The current algorithm has some limitations:
+
+ - The result is undefined for points exactly at the boundary
+ (i.e. at the path shifted by *radius/2*).
+ - The result is undefined if there is no enclosed area, i.e. all
+ vertices are on a straight line.
+ - If bounding lines start to cross each other due to *radius* shift,
+ the result is not guaranteed to be correct.
+ """
+ if transform is not None:
+ transform = transform.frozen()
+ # `point_in_path` does not handle nonlinear transforms, so we
+ # transform the path ourselves. If *transform* is affine, letting
+ # `point_in_path` handle the transform avoids allocating an extra
+ # buffer.
+ if transform and not transform.is_affine:
+ self = transform.transform_path(self)
+ transform = None
+ return _path.point_in_path(point[0], point[1], radius, self, transform)
+
+ def contains_points(self, points, transform=None, radius=0.0):
+ """
+ Return whether the area enclosed by the path contains the given points.
+
+ The path is always treated as closed; i.e. if the last code is not
+ CLOSEPOLY an implicit segment connecting the last vertex to the first
+ vertex is assumed.
+
+ Parameters
+ ----------
+ points : (N, 2) array
+ The points to check. Columns contain x and y values.
+ transform : `matplotlib.transforms.Transform`, optional
+ If not ``None``, *points* will be compared to ``self`` transformed
+ by *transform*; i.e. for a correct check, *transform* should
+ transform the path into the coordinate system of *points*.
+ radius : float, default: 0
+ Additional margin on the path in coordinates of *points*.
+ The path is extended tangentially by *radius/2*; i.e. if you would
+ draw the path with a linewidth of *radius*, all points on the line
+ would still be considered to be contained in the area. Conversely,
+ negative values shrink the area: Points on the imaginary line
+ will be considered outside the area.
+
+ Returns
+ -------
+ length-N bool array
+
+ Notes
+ -----
+ The current algorithm has some limitations:
+
+ - The result is undefined for points exactly at the boundary
+ (i.e. at the path shifted by *radius/2*).
+ - The result is undefined if there is no enclosed area, i.e. all
+ vertices are on a straight line.
+ - If bounding lines start to cross each other due to *radius* shift,
+ the result is not guaranteed to be correct.
+ """
+ if transform is not None:
+ transform = transform.frozen()
+ result = _path.points_in_path(points, radius, self, transform)
+ return result.astype('bool')
+
+ def contains_path(self, path, transform=None):
+ """
+ Return whether this (closed) path completely contains the given path.
+
+ If *transform* is not ``None``, the path will be transformed before
+ checking for containment.
+ """
+ if transform is not None:
+ transform = transform.frozen()
+ return _path.path_in_path(self, None, path, transform)
+
+ def get_extents(self, transform=None, **kwargs):
+ """
+ Get Bbox of the path.
+
+ Parameters
+ ----------
+ transform : matplotlib.transforms.Transform, optional
+ Transform to apply to path before computing extents, if any.
+ **kwargs
+ Forwarded to `.iter_bezier`.
+
+ Returns
+ -------
+ matplotlib.transforms.Bbox
+ The extents of the path Bbox([[xmin, ymin], [xmax, ymax]])
+ """
+ from .transforms import Bbox
+ if transform is not None:
+ self = transform.transform_path(self)
+ if self.codes is None:
+ xys = self.vertices
+ elif len(np.intersect1d(self.codes, [Path.CURVE3, Path.CURVE4])) == 0:
+ # Optimization for the straight line case.
+ # Instead of iterating through each curve, consider
+ # each line segment's end-points
+ # (recall that STOP and CLOSEPOLY vertices are ignored)
+ xys = self.vertices[np.isin(self.codes,
+ [Path.MOVETO, Path.LINETO])]
+ else:
+ xys = []
+ for curve, code in self.iter_bezier(**kwargs):
+ # places where the derivative is zero can be extrema
+ _, dzeros = curve.axis_aligned_extrema()
+ # as can the ends of the curve
+ xys.append(curve([0, *dzeros, 1]))
+ xys = np.concatenate(xys)
+ if len(xys):
+ return Bbox([xys.min(axis=0), xys.max(axis=0)])
+ else:
+ return Bbox.null()
+
+ def intersects_path(self, other, filled=True):
+ """
+ Return whether if this path intersects another given path.
+
+ If *filled* is True, then this also returns True if one path completely
+ encloses the other (i.e., the paths are treated as filled).
+ """
+ return _path.path_intersects_path(self, other, filled)
+
+ def intersects_bbox(self, bbox, filled=True):
+ """
+ Return whether this path intersects a given `~.transforms.Bbox`.
+
+ If *filled* is True, then this also returns True if the path completely
+ encloses the `.Bbox` (i.e., the path is treated as filled).
+
+ The bounding box is always considered filled.
+ """
+ return _path.path_intersects_rectangle(
+ self, bbox.x0, bbox.y0, bbox.x1, bbox.y1, filled)
+
+ def interpolated(self, steps):
+ """
+ Return a new path resampled to length N x steps.
+
+ Codes other than LINETO are not handled correctly.
+ """
+ if steps == 1:
+ return self
+
+ vertices = simple_linear_interpolation(self.vertices, steps)
+ codes = self.codes
+ if codes is not None:
+ new_codes = np.full((len(codes) - 1) * steps + 1, Path.LINETO,
+ dtype=self.code_type)
+ new_codes[0::steps] = codes
+ else:
+ new_codes = None
+ return Path(vertices, new_codes)
+
+ def to_polygons(self, transform=None, width=0, height=0, closed_only=True):
+ """
+ Convert this path to a list of polygons or polylines. Each
+ polygon/polyline is an Nx2 array of vertices. In other words,
+ each polygon has no ``MOVETO`` instructions or curves. This
+ is useful for displaying in backends that do not support
+ compound paths or Bézier curves.
+
+ If *width* and *height* are both non-zero then the lines will
+ be simplified so that vertices outside of (0, 0), (width,
+ height) will be clipped.
+
+ If *closed_only* is `True` (default), only closed polygons,
+ with the last point being the same as the first point, will be
+ returned. Any unclosed polylines in the path will be
+ explicitly closed. If *closed_only* is `False`, any unclosed
+ polygons in the path will be returned as unclosed polygons,
+ and the closed polygons will be returned explicitly closed by
+ setting the last point to the same as the first point.
+ """
+ if len(self.vertices) == 0:
+ return []
+
+ if transform is not None:
+ transform = transform.frozen()
+
+ if self.codes is None and (width == 0 or height == 0):
+ vertices = self.vertices
+ if closed_only:
+ if len(vertices) < 3:
+ return []
+ elif np.any(vertices[0] != vertices[-1]):
+ vertices = [*vertices, vertices[0]]
+
+ if transform is None:
+ return [vertices]
+ else:
+ return [transform.transform(vertices)]
+
+ # Deal with the case where there are curves and/or multiple
+ # subpaths (using extension code)
+ return _path.convert_path_to_polygons(
+ self, transform, width, height, closed_only)
+
+ _unit_rectangle = None
+
+ @classmethod
+ def unit_rectangle(cls):
+ """
+ Return a `Path` instance of the unit rectangle from (0, 0) to (1, 1).
+ """
+ if cls._unit_rectangle is None:
+ cls._unit_rectangle = cls([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]],
+ closed=True, readonly=True)
+ return cls._unit_rectangle
+
+ _unit_regular_polygons = WeakValueDictionary()
+
+ @classmethod
+ def unit_regular_polygon(cls, numVertices):
+ """
+ Return a :class:`Path` instance for a unit regular polygon with the
+ given *numVertices* such that the circumscribing circle has radius 1.0,
+ centered at (0, 0).
+ """
+ if numVertices <= 16:
+ path = cls._unit_regular_polygons.get(numVertices)
+ else:
+ path = None
+ if path is None:
+ theta = ((2 * np.pi / numVertices) * np.arange(numVertices + 1)
+ # This initial rotation is to make sure the polygon always
+ # "points-up".
+ + np.pi / 2)
+ verts = np.column_stack((np.cos(theta), np.sin(theta)))
+ path = cls(verts, closed=True, readonly=True)
+ if numVertices <= 16:
+ cls._unit_regular_polygons[numVertices] = path
+ return path
+
+ _unit_regular_stars = WeakValueDictionary()
+
+ @classmethod
+ def unit_regular_star(cls, numVertices, innerCircle=0.5):
+ """
+ Return a :class:`Path` for a unit regular star with the given
+ numVertices and radius of 1.0, centered at (0, 0).
+ """
+ if numVertices <= 16:
+ path = cls._unit_regular_stars.get((numVertices, innerCircle))
+ else:
+ path = None
+ if path is None:
+ ns2 = numVertices * 2
+ theta = (2*np.pi/ns2 * np.arange(ns2 + 1))
+ # This initial rotation is to make sure the polygon always
+ # "points-up"
+ theta += np.pi / 2.0
+ r = np.ones(ns2 + 1)
+ r[1::2] = innerCircle
+ verts = (r * np.vstack((np.cos(theta), np.sin(theta)))).T
+ path = cls(verts, closed=True, readonly=True)
+ if numVertices <= 16:
+ cls._unit_regular_stars[(numVertices, innerCircle)] = path
+ return path
+
+ @classmethod
+ def unit_regular_asterisk(cls, numVertices):
+ """
+ Return a :class:`Path` for a unit regular asterisk with the given
+ numVertices and radius of 1.0, centered at (0, 0).
+ """
+ return cls.unit_regular_star(numVertices, 0.0)
+
+ _unit_circle = None
+
+ @classmethod
+ def unit_circle(cls):
+ """
+ Return the readonly :class:`Path` of the unit circle.
+
+ For most cases, :func:`Path.circle` will be what you want.
+ """
+ if cls._unit_circle is None:
+ cls._unit_circle = cls.circle(center=(0, 0), radius=1,
+ readonly=True)
+ return cls._unit_circle
+
+ @classmethod
+ def circle(cls, center=(0., 0.), radius=1., readonly=False):
+ """
+ Return a `Path` representing a circle of a given radius and center.
+
+ Parameters
+ ----------
+ center : (float, float), default: (0, 0)
+ The center of the circle.
+ radius : float, default: 1
+ The radius of the circle.
+ readonly : bool
+ Whether the created path should have the "readonly" argument
+ set when creating the Path instance.
+
+ Notes
+ -----
+ The circle is approximated using 8 cubic Bézier curves, as described in
+
+ Lancaster, Don. `Approximating a Circle or an Ellipse Using Four
+ Bezier Cubic Splines `_.
+ """
+ MAGIC = 0.2652031
+ SQRTHALF = np.sqrt(0.5)
+ MAGIC45 = SQRTHALF * MAGIC
+
+ vertices = np.array([[0.0, -1.0],
+
+ [MAGIC, -1.0],
+ [SQRTHALF-MAGIC45, -SQRTHALF-MAGIC45],
+ [SQRTHALF, -SQRTHALF],
+
+ [SQRTHALF+MAGIC45, -SQRTHALF+MAGIC45],
+ [1.0, -MAGIC],
+ [1.0, 0.0],
+
+ [1.0, MAGIC],
+ [SQRTHALF+MAGIC45, SQRTHALF-MAGIC45],
+ [SQRTHALF, SQRTHALF],
+
+ [SQRTHALF-MAGIC45, SQRTHALF+MAGIC45],
+ [MAGIC, 1.0],
+ [0.0, 1.0],
+
+ [-MAGIC, 1.0],
+ [-SQRTHALF+MAGIC45, SQRTHALF+MAGIC45],
+ [-SQRTHALF, SQRTHALF],
+
+ [-SQRTHALF-MAGIC45, SQRTHALF-MAGIC45],
+ [-1.0, MAGIC],
+ [-1.0, 0.0],
+
+ [-1.0, -MAGIC],
+ [-SQRTHALF-MAGIC45, -SQRTHALF+MAGIC45],
+ [-SQRTHALF, -SQRTHALF],
+
+ [-SQRTHALF+MAGIC45, -SQRTHALF-MAGIC45],
+ [-MAGIC, -1.0],
+ [0.0, -1.0],
+
+ [0.0, -1.0]],
+ dtype=float)
+
+ codes = [cls.CURVE4] * 26
+ codes[0] = cls.MOVETO
+ codes[-1] = cls.CLOSEPOLY
+ return Path(vertices * radius + center, codes, readonly=readonly)
+
+ _unit_circle_righthalf = None
+
+ @classmethod
+ def unit_circle_righthalf(cls):
+ """
+ Return a `Path` of the right half of a unit circle.
+
+ See `Path.circle` for the reference on the approximation used.
+ """
+ if cls._unit_circle_righthalf is None:
+ MAGIC = 0.2652031
+ SQRTHALF = np.sqrt(0.5)
+ MAGIC45 = SQRTHALF * MAGIC
+
+ vertices = np.array(
+ [[0.0, -1.0],
+
+ [MAGIC, -1.0],
+ [SQRTHALF-MAGIC45, -SQRTHALF-MAGIC45],
+ [SQRTHALF, -SQRTHALF],
+
+ [SQRTHALF+MAGIC45, -SQRTHALF+MAGIC45],
+ [1.0, -MAGIC],
+ [1.0, 0.0],
+
+ [1.0, MAGIC],
+ [SQRTHALF+MAGIC45, SQRTHALF-MAGIC45],
+ [SQRTHALF, SQRTHALF],
+
+ [SQRTHALF-MAGIC45, SQRTHALF+MAGIC45],
+ [MAGIC, 1.0],
+ [0.0, 1.0],
+
+ [0.0, -1.0]],
+
+ float)
+
+ codes = np.full(14, cls.CURVE4, dtype=cls.code_type)
+ codes[0] = cls.MOVETO
+ codes[-1] = cls.CLOSEPOLY
+
+ cls._unit_circle_righthalf = cls(vertices, codes, readonly=True)
+ return cls._unit_circle_righthalf
+
+ @classmethod
+ def arc(cls, theta1, theta2, n=None, is_wedge=False):
+ """
+ Return a `Path` for the unit circle arc from angles *theta1* to
+ *theta2* (in degrees).
+
+ *theta2* is unwrapped to produce the shortest arc within 360 degrees.
+ That is, if *theta2* > *theta1* + 360, the arc will be from *theta1* to
+ *theta2* - 360 and not a full circle plus some extra overlap.
+
+ If *n* is provided, it is the number of spline segments to make.
+ If *n* is not provided, the number of spline segments is
+ determined based on the delta between *theta1* and *theta2*.
+
+ Masionobe, L. 2003. `Drawing an elliptical arc using
+ polylines, quadratic or cubic Bezier curves
+ `_.
+ """
+ halfpi = np.pi * 0.5
+
+ eta1 = theta1
+ eta2 = theta2 - 360 * np.floor((theta2 - theta1) / 360)
+ # Ensure 2pi range is not flattened to 0 due to floating-point errors,
+ # but don't try to expand existing 0 range.
+ if theta2 != theta1 and eta2 <= eta1:
+ eta2 += 360
+ eta1, eta2 = np.deg2rad([eta1, eta2])
+
+ # number of curve segments to make
+ if n is None:
+ n = int(2 ** np.ceil((eta2 - eta1) / halfpi))
+ if n < 1:
+ raise ValueError("n must be >= 1 or None")
+
+ deta = (eta2 - eta1) / n
+ t = np.tan(0.5 * deta)
+ alpha = np.sin(deta) * (np.sqrt(4.0 + 3.0 * t * t) - 1) / 3.0
+
+ steps = np.linspace(eta1, eta2, n + 1, True)
+ cos_eta = np.cos(steps)
+ sin_eta = np.sin(steps)
+
+ xA = cos_eta[:-1]
+ yA = sin_eta[:-1]
+ xA_dot = -yA
+ yA_dot = xA
+
+ xB = cos_eta[1:]
+ yB = sin_eta[1:]
+ xB_dot = -yB
+ yB_dot = xB
+
+ if is_wedge:
+ length = n * 3 + 4
+ vertices = np.zeros((length, 2), float)
+ codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
+ vertices[1] = [xA[0], yA[0]]
+ codes[0:2] = [cls.MOVETO, cls.LINETO]
+ codes[-2:] = [cls.LINETO, cls.CLOSEPOLY]
+ vertex_offset = 2
+ end = length - 2
+ else:
+ length = n * 3 + 1
+ vertices = np.empty((length, 2), float)
+ codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
+ vertices[0] = [xA[0], yA[0]]
+ codes[0] = cls.MOVETO
+ vertex_offset = 1
+ end = length
+
+ vertices[vertex_offset:end:3, 0] = xA + alpha * xA_dot
+ vertices[vertex_offset:end:3, 1] = yA + alpha * yA_dot
+ vertices[vertex_offset+1:end:3, 0] = xB - alpha * xB_dot
+ vertices[vertex_offset+1:end:3, 1] = yB - alpha * yB_dot
+ vertices[vertex_offset+2:end:3, 0] = xB
+ vertices[vertex_offset+2:end:3, 1] = yB
+
+ return cls(vertices, codes, readonly=True)
+
+ @classmethod
+ def wedge(cls, theta1, theta2, n=None):
+ """
+ Return a `Path` for the unit circle wedge from angles *theta1* to
+ *theta2* (in degrees).
+
+ *theta2* is unwrapped to produce the shortest wedge within 360 degrees.
+ That is, if *theta2* > *theta1* + 360, the wedge will be from *theta1*
+ to *theta2* - 360 and not a full circle plus some extra overlap.
+
+ If *n* is provided, it is the number of spline segments to make.
+ If *n* is not provided, the number of spline segments is
+ determined based on the delta between *theta1* and *theta2*.
+
+ See `Path.arc` for the reference on the approximation used.
+ """
+ return cls.arc(theta1, theta2, n, True)
+
+ @staticmethod
+ @lru_cache(8)
+ def hatch(hatchpattern, density=6):
+ """
+ Given a hatch specifier, *hatchpattern*, generates a Path that
+ can be used in a repeated hatching pattern. *density* is the
+ number of lines per unit square.
+ """
+ from matplotlib.hatch import get_path
+ return (get_path(hatchpattern, density)
+ if hatchpattern is not None else None)
+
+ def clip_to_bbox(self, bbox, inside=True):
+ """
+ Clip the path to the given bounding box.
+
+ The path must be made up of one or more closed polygons. This
+ algorithm will not behave correctly for unclosed paths.
+
+ If *inside* is `True`, clip to the inside of the box, otherwise
+ to the outside of the box.
+ """
+ verts = _path.clip_path_to_rect(self, bbox, inside)
+ paths = [Path(poly) for poly in verts]
+ return self.make_compound_path(*paths)
+
+
+def get_path_collection_extents(
+ master_transform, paths, transforms, offsets, offset_transform):
+ r"""
+ Get bounding box of a `.PathCollection`\s internal objects.
+
+ That is, given a sequence of `Path`\s, `.Transform`\s objects, and offsets, as found
+ in a `.PathCollection`, return the bounding box that encapsulates all of them.
+
+ Parameters
+ ----------
+ master_transform : `.Transform`
+ Global transformation applied to all paths.
+ paths : list of `Path`
+ transforms : list of `.Affine2D`
+ offsets : (N, 2) array-like
+ offset_transform : `.Affine2D`
+ Transform applied to the offsets before offsetting the path.
+
+ Notes
+ -----
+ The way that *paths*, *transforms* and *offsets* are combined follows the same
+ method as for collections: each is iterated over independently, so if you have 3
+ paths (A, B, C), 2 transforms (α, β) and 1 offset (O), their combinations are as
+ follows:
+
+ - (A, α, O)
+ - (B, β, O)
+ - (C, α, O)
+ """
+ from .transforms import Bbox
+ if len(paths) == 0:
+ raise ValueError("No paths provided")
+ extents, minpos = _path.get_path_collection_extents(
+ master_transform, paths, np.atleast_3d(transforms),
+ offsets, offset_transform)
+ return Bbox.from_extents(*extents, minpos=minpos)
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/patheffects.py b/omnilmm/lib/python3.10/site-packages/matplotlib/patheffects.py
new file mode 100644
index 0000000000000000000000000000000000000000..de72d7cd9ff5cf77fc662b589341d7f68a593538
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/patheffects.py
@@ -0,0 +1,513 @@
+"""
+Defines classes for path effects. The path effects are supported in `.Text`,
+`.Line2D` and `.Patch`.
+
+.. seealso::
+ :doc:`/tutorials/advanced/patheffects_guide`
+"""
+
+from matplotlib.backend_bases import RendererBase
+from matplotlib import colors as mcolors
+from matplotlib import patches as mpatches
+from matplotlib import transforms as mtransforms
+from matplotlib.path import Path
+import numpy as np
+
+
+class AbstractPathEffect:
+ """
+ A base class for path effects.
+
+ Subclasses should override the ``draw_path`` method to add effect
+ functionality.
+ """
+
+ def __init__(self, offset=(0., 0.)):
+ """
+ Parameters
+ ----------
+ offset : (float, float), default: (0, 0)
+ The (x, y) offset to apply to the path, measured in points.
+ """
+ self._offset = offset
+
+ def _offset_transform(self, renderer):
+ """Apply the offset to the given transform."""
+ return mtransforms.Affine2D().translate(
+ *map(renderer.points_to_pixels, self._offset))
+
+ def _update_gc(self, gc, new_gc_dict):
+ """
+ Update the given GraphicsContext with the given dict of properties.
+
+ The keys in the dictionary are used to identify the appropriate
+ ``set_`` method on the *gc*.
+ """
+ new_gc_dict = new_gc_dict.copy()
+
+ dashes = new_gc_dict.pop("dashes", None)
+ if dashes:
+ gc.set_dashes(**dashes)
+
+ for k, v in new_gc_dict.items():
+ set_method = getattr(gc, 'set_' + k, None)
+ if not callable(set_method):
+ raise AttributeError('Unknown property {0}'.format(k))
+ set_method(v)
+ return gc
+
+ def draw_path(self, renderer, gc, tpath, affine, rgbFace=None):
+ """
+ Derived should override this method. The arguments are the same
+ as :meth:`matplotlib.backend_bases.RendererBase.draw_path`
+ except the first argument is a renderer.
+ """
+ # Get the real renderer, not a PathEffectRenderer.
+ if isinstance(renderer, PathEffectRenderer):
+ renderer = renderer._renderer
+ return renderer.draw_path(gc, tpath, affine, rgbFace)
+
+
+class PathEffectRenderer(RendererBase):
+ """
+ Implements a Renderer which contains another renderer.
+
+ This proxy then intercepts draw calls, calling the appropriate
+ :class:`AbstractPathEffect` draw method.
+
+ .. note::
+ Not all methods have been overridden on this RendererBase subclass.
+ It may be necessary to add further methods to extend the PathEffects
+ capabilities further.
+ """
+
+ def __init__(self, path_effects, renderer):
+ """
+ Parameters
+ ----------
+ path_effects : iterable of :class:`AbstractPathEffect`
+ The path effects which this renderer represents.
+ renderer : `~matplotlib.backend_bases.RendererBase` subclass
+
+ """
+ self._path_effects = path_effects
+ self._renderer = renderer
+
+ def copy_with_path_effect(self, path_effects):
+ return self.__class__(path_effects, self._renderer)
+
+ def draw_path(self, gc, tpath, affine, rgbFace=None):
+ for path_effect in self._path_effects:
+ path_effect.draw_path(self._renderer, gc, tpath, affine,
+ rgbFace)
+
+ def draw_markers(
+ self, gc, marker_path, marker_trans, path, *args, **kwargs):
+ # We do a little shimmy so that all markers are drawn for each path
+ # effect in turn. Essentially, we induce recursion (depth 1) which is
+ # terminated once we have just a single path effect to work with.
+ if len(self._path_effects) == 1:
+ # Call the base path effect function - this uses the unoptimised
+ # approach of calling "draw_path" multiple times.
+ return super().draw_markers(gc, marker_path, marker_trans, path,
+ *args, **kwargs)
+
+ for path_effect in self._path_effects:
+ renderer = self.copy_with_path_effect([path_effect])
+ # Recursively call this method, only next time we will only have
+ # one path effect.
+ renderer.draw_markers(gc, marker_path, marker_trans, path,
+ *args, **kwargs)
+
+ def draw_path_collection(self, gc, master_transform, paths, *args,
+ **kwargs):
+ # We do a little shimmy so that all paths are drawn for each path
+ # effect in turn. Essentially, we induce recursion (depth 1) which is
+ # terminated once we have just a single path effect to work with.
+ if len(self._path_effects) == 1:
+ # Call the base path effect function - this uses the unoptimised
+ # approach of calling "draw_path" multiple times.
+ return super().draw_path_collection(gc, master_transform, paths,
+ *args, **kwargs)
+
+ for path_effect in self._path_effects:
+ renderer = self.copy_with_path_effect([path_effect])
+ # Recursively call this method, only next time we will only have
+ # one path effect.
+ renderer.draw_path_collection(gc, master_transform, paths,
+ *args, **kwargs)
+
+ def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath):
+ # Implements the naive text drawing as is found in RendererBase.
+ path, transform = self._get_text_path_transform(x, y, s, prop,
+ angle, ismath)
+ color = gc.get_rgb()
+ gc.set_linewidth(0.0)
+ self.draw_path(gc, path, transform, rgbFace=color)
+
+ def __getattribute__(self, name):
+ if name in ['flipy', 'get_canvas_width_height', 'new_gc',
+ 'points_to_pixels', '_text2path', 'height', 'width']:
+ return getattr(self._renderer, name)
+ else:
+ return object.__getattribute__(self, name)
+
+
+class Normal(AbstractPathEffect):
+ """
+ The "identity" PathEffect.
+
+ The Normal PathEffect's sole purpose is to draw the original artist with
+ no special path effect.
+ """
+
+
+def _subclass_with_normal(effect_class):
+ """
+ Create a PathEffect class combining *effect_class* and a normal draw.
+ """
+
+ class withEffect(effect_class):
+ def draw_path(self, renderer, gc, tpath, affine, rgbFace):
+ super().draw_path(renderer, gc, tpath, affine, rgbFace)
+ renderer.draw_path(gc, tpath, affine, rgbFace)
+
+ withEffect.__name__ = f"with{effect_class.__name__}"
+ withEffect.__qualname__ = f"with{effect_class.__name__}"
+ withEffect.__doc__ = f"""
+ A shortcut PathEffect for applying `.{effect_class.__name__}` and then
+ drawing the original Artist.
+
+ With this class you can use ::
+
+ artist.set_path_effects([path_effects.with{effect_class.__name__}()])
+
+ as a shortcut for ::
+
+ artist.set_path_effects([path_effects.{effect_class.__name__}(),
+ path_effects.Normal()])
+ """
+ # Docstring inheritance doesn't work for locally-defined subclasses.
+ withEffect.draw_path.__doc__ = effect_class.draw_path.__doc__
+ return withEffect
+
+
+class Stroke(AbstractPathEffect):
+ """A line based PathEffect which re-draws a stroke."""
+
+ def __init__(self, offset=(0, 0), **kwargs):
+ """
+ The path will be stroked with its gc updated with the given
+ keyword arguments, i.e., the keyword arguments should be valid
+ gc parameter values.
+ """
+ super().__init__(offset)
+ self._gc = kwargs
+
+ def draw_path(self, renderer, gc, tpath, affine, rgbFace):
+ """Draw the path with updated gc."""
+ gc0 = renderer.new_gc() # Don't modify gc, but a copy!
+ gc0.copy_properties(gc)
+ gc0 = self._update_gc(gc0, self._gc)
+ renderer.draw_path(
+ gc0, tpath, affine + self._offset_transform(renderer), rgbFace)
+ gc0.restore()
+
+
+withStroke = _subclass_with_normal(effect_class=Stroke)
+
+
+class SimplePatchShadow(AbstractPathEffect):
+ """A simple shadow via a filled patch."""
+
+ def __init__(self, offset=(2, -2),
+ shadow_rgbFace=None, alpha=None,
+ rho=0.3, **kwargs):
+ """
+ Parameters
+ ----------
+ offset : (float, float), default: (2, -2)
+ The (x, y) offset of the shadow in points.
+ shadow_rgbFace : color
+ The shadow color.
+ alpha : float, default: 0.3
+ The alpha transparency of the created shadow patch.
+ rho : float, default: 0.3
+ A scale factor to apply to the rgbFace color if *shadow_rgbFace*
+ is not specified.
+ **kwargs
+ Extra keywords are stored and passed through to
+ :meth:`AbstractPathEffect._update_gc`.
+
+ """
+ super().__init__(offset)
+
+ if shadow_rgbFace is None:
+ self._shadow_rgbFace = shadow_rgbFace
+ else:
+ self._shadow_rgbFace = mcolors.to_rgba(shadow_rgbFace)
+
+ if alpha is None:
+ alpha = 0.3
+
+ self._alpha = alpha
+ self._rho = rho
+
+ #: The dictionary of keywords to update the graphics collection with.
+ self._gc = kwargs
+
+ def draw_path(self, renderer, gc, tpath, affine, rgbFace):
+ """
+ Overrides the standard draw_path to add the shadow offset and
+ necessary color changes for the shadow.
+ """
+ gc0 = renderer.new_gc() # Don't modify gc, but a copy!
+ gc0.copy_properties(gc)
+
+ if self._shadow_rgbFace is None:
+ r, g, b = (rgbFace or (1., 1., 1.))[:3]
+ # Scale the colors by a factor to improve the shadow effect.
+ shadow_rgbFace = (r * self._rho, g * self._rho, b * self._rho)
+ else:
+ shadow_rgbFace = self._shadow_rgbFace
+
+ gc0.set_foreground("none")
+ gc0.set_alpha(self._alpha)
+ gc0.set_linewidth(0)
+
+ gc0 = self._update_gc(gc0, self._gc)
+ renderer.draw_path(
+ gc0, tpath, affine + self._offset_transform(renderer),
+ shadow_rgbFace)
+ gc0.restore()
+
+
+withSimplePatchShadow = _subclass_with_normal(effect_class=SimplePatchShadow)
+
+
+class SimpleLineShadow(AbstractPathEffect):
+ """A simple shadow via a line."""
+
+ def __init__(self, offset=(2, -2),
+ shadow_color='k', alpha=0.3, rho=0.3, **kwargs):
+ """
+ Parameters
+ ----------
+ offset : (float, float), default: (2, -2)
+ The (x, y) offset to apply to the path, in points.
+ shadow_color : color, default: 'black'
+ The shadow color.
+ A value of ``None`` takes the original artist's color
+ with a scale factor of *rho*.
+ alpha : float, default: 0.3
+ The alpha transparency of the created shadow patch.
+ rho : float, default: 0.3
+ A scale factor to apply to the rgbFace color if *shadow_color*
+ is ``None``.
+ **kwargs
+ Extra keywords are stored and passed through to
+ :meth:`AbstractPathEffect._update_gc`.
+ """
+ super().__init__(offset)
+ if shadow_color is None:
+ self._shadow_color = shadow_color
+ else:
+ self._shadow_color = mcolors.to_rgba(shadow_color)
+ self._alpha = alpha
+ self._rho = rho
+ #: The dictionary of keywords to update the graphics collection with.
+ self._gc = kwargs
+
+ def draw_path(self, renderer, gc, tpath, affine, rgbFace):
+ """
+ Overrides the standard draw_path to add the shadow offset and
+ necessary color changes for the shadow.
+ """
+ gc0 = renderer.new_gc() # Don't modify gc, but a copy!
+ gc0.copy_properties(gc)
+
+ if self._shadow_color is None:
+ r, g, b = (gc0.get_foreground() or (1., 1., 1.))[:3]
+ # Scale the colors by a factor to improve the shadow effect.
+ shadow_rgbFace = (r * self._rho, g * self._rho, b * self._rho)
+ else:
+ shadow_rgbFace = self._shadow_color
+
+ gc0.set_foreground(shadow_rgbFace)
+ gc0.set_alpha(self._alpha)
+
+ gc0 = self._update_gc(gc0, self._gc)
+ renderer.draw_path(
+ gc0, tpath, affine + self._offset_transform(renderer))
+ gc0.restore()
+
+
+class PathPatchEffect(AbstractPathEffect):
+ """
+ Draws a `.PathPatch` instance whose Path comes from the original
+ PathEffect artist.
+ """
+
+ def __init__(self, offset=(0, 0), **kwargs):
+ """
+ Parameters
+ ----------
+ offset : (float, float), default: (0, 0)
+ The (x, y) offset to apply to the path, in points.
+ **kwargs
+ All keyword arguments are passed through to the
+ :class:`~matplotlib.patches.PathPatch` constructor. The
+ properties which cannot be overridden are "path", "clip_box"
+ "transform" and "clip_path".
+ """
+ super().__init__(offset=offset)
+ self.patch = mpatches.PathPatch([], **kwargs)
+
+ def draw_path(self, renderer, gc, tpath, affine, rgbFace):
+ self.patch._path = tpath
+ self.patch.set_transform(affine + self._offset_transform(renderer))
+ self.patch.set_clip_box(gc.get_clip_rectangle())
+ clip_path = gc.get_clip_path()
+ if clip_path:
+ self.patch.set_clip_path(*clip_path)
+ self.patch.draw(renderer)
+
+
+class TickedStroke(AbstractPathEffect):
+ """
+ A line-based PathEffect which draws a path with a ticked style.
+
+ This line style is frequently used to represent constraints in
+ optimization. The ticks may be used to indicate that one side
+ of the line is invalid or to represent a closed boundary of a
+ domain (i.e. a wall or the edge of a pipe).
+
+ The spacing, length, and angle of ticks can be controlled.
+
+ This line style is sometimes referred to as a hatched line.
+
+ See also the :doc:`/gallery/misc/tickedstroke_demo` example.
+ """
+
+ def __init__(self, offset=(0, 0),
+ spacing=10.0, angle=45.0, length=np.sqrt(2),
+ **kwargs):
+ """
+ Parameters
+ ----------
+ offset : (float, float), default: (0, 0)
+ The (x, y) offset to apply to the path, in points.
+ spacing : float, default: 10.0
+ The spacing between ticks in points.
+ angle : float, default: 45.0
+ The angle between the path and the tick in degrees. The angle
+ is measured as if you were an ant walking along the curve, with
+ zero degrees pointing directly ahead, 90 to your left, -90
+ to your right, and 180 behind you. To change side of the ticks,
+ change sign of the angle.
+ length : float, default: 1.414
+ The length of the tick relative to spacing.
+ Recommended length = 1.414 (sqrt(2)) when angle=45, length=1.0
+ when angle=90 and length=2.0 when angle=60.
+ **kwargs
+ Extra keywords are stored and passed through to
+ :meth:`AbstractPathEffect._update_gc`.
+
+ Examples
+ --------
+ See :doc:`/gallery/misc/tickedstroke_demo`.
+ """
+ super().__init__(offset)
+
+ self._spacing = spacing
+ self._angle = angle
+ self._length = length
+ self._gc = kwargs
+
+ def draw_path(self, renderer, gc, tpath, affine, rgbFace):
+ """Draw the path with updated gc."""
+ # Do not modify the input! Use copy instead.
+ gc0 = renderer.new_gc()
+ gc0.copy_properties(gc)
+
+ gc0 = self._update_gc(gc0, self._gc)
+ trans = affine + self._offset_transform(renderer)
+
+ theta = -np.radians(self._angle)
+ trans_matrix = np.array([[np.cos(theta), -np.sin(theta)],
+ [np.sin(theta), np.cos(theta)]])
+
+ # Convert spacing parameter to pixels.
+ spacing_px = renderer.points_to_pixels(self._spacing)
+
+ # Transform before evaluation because to_polygons works at resolution
+ # of one -- assuming it is working in pixel space.
+ transpath = affine.transform_path(tpath)
+
+ # Evaluate path to straight line segments that can be used to
+ # construct line ticks.
+ polys = transpath.to_polygons(closed_only=False)
+
+ for p in polys:
+ x = p[:, 0]
+ y = p[:, 1]
+
+ # Can not interpolate points or draw line if only one point in
+ # polyline.
+ if x.size < 2:
+ continue
+
+ # Find distance between points on the line
+ ds = np.hypot(x[1:] - x[:-1], y[1:] - y[:-1])
+
+ # Build parametric coordinate along curve
+ s = np.concatenate(([0.0], np.cumsum(ds)))
+ s_total = s[-1]
+
+ num = int(np.ceil(s_total / spacing_px)) - 1
+ # Pick parameter values for ticks.
+ s_tick = np.linspace(spacing_px/2, s_total - spacing_px/2, num)
+
+ # Find points along the parameterized curve
+ x_tick = np.interp(s_tick, s, x)
+ y_tick = np.interp(s_tick, s, y)
+
+ # Find unit vectors in local direction of curve
+ delta_s = self._spacing * .001
+ u = (np.interp(s_tick + delta_s, s, x) - x_tick) / delta_s
+ v = (np.interp(s_tick + delta_s, s, y) - y_tick) / delta_s
+
+ # Normalize slope into unit slope vector.
+ n = np.hypot(u, v)
+ mask = n == 0
+ n[mask] = 1.0
+
+ uv = np.array([u / n, v / n]).T
+ uv[mask] = np.array([0, 0]).T
+
+ # Rotate and scale unit vector into tick vector
+ dxy = np.dot(uv, trans_matrix) * self._length * spacing_px
+
+ # Build tick endpoints
+ x_end = x_tick + dxy[:, 0]
+ y_end = y_tick + dxy[:, 1]
+
+ # Interleave ticks to form Path vertices
+ xyt = np.empty((2 * num, 2), dtype=x_tick.dtype)
+ xyt[0::2, 0] = x_tick
+ xyt[1::2, 0] = x_end
+ xyt[0::2, 1] = y_tick
+ xyt[1::2, 1] = y_end
+
+ # Build up vector of Path codes
+ codes = np.tile([Path.MOVETO, Path.LINETO], num)
+
+ # Construct and draw resulting path
+ h = Path(xyt, codes)
+ # Transform back to data space during render
+ renderer.draw_path(gc0, h, affine.inverted() + trans, rgbFace)
+
+ gc0.restore()
+
+
+withTickedStroke = _subclass_with_normal(effect_class=TickedStroke)
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/pylab.py b/omnilmm/lib/python3.10/site-packages/matplotlib/pylab.py
new file mode 100644
index 0000000000000000000000000000000000000000..62fced0f7bcccaa8a916ca365b9ebb7d43300260
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/pylab.py
@@ -0,0 +1,55 @@
+"""
+.. warning::
+ Since heavily importing into the global namespace may result in unexpected
+ behavior, the use of pylab is strongly discouraged. Use `matplotlib.pyplot`
+ instead.
+
+`pylab` is a module that includes `matplotlib.pyplot`, `numpy`, `numpy.fft`,
+`numpy.linalg`, `numpy.random`, and some additional functions, all within
+a single namespace. Its original purpose was to mimic a MATLAB-like way
+of working by importing all functions into the global namespace. This is
+considered bad style nowadays.
+"""
+
+from matplotlib.cbook import flatten, silent_list
+
+import matplotlib as mpl
+
+from matplotlib.dates import (
+ date2num, num2date, datestr2num, drange, DateFormatter, DateLocator,
+ RRuleLocator, YearLocator, MonthLocator, WeekdayLocator, DayLocator,
+ HourLocator, MinuteLocator, SecondLocator, rrule, MO, TU, WE, TH, FR,
+ SA, SU, YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY,
+ relativedelta)
+
+# bring all the symbols in so folks can import them from
+# pylab in one fell swoop
+
+## We are still importing too many things from mlab; more cleanup is needed.
+
+from matplotlib.mlab import (
+ detrend, detrend_linear, detrend_mean, detrend_none, window_hanning,
+ window_none)
+
+from matplotlib import cbook, mlab, pyplot as plt
+from matplotlib.pyplot import *
+
+from numpy import *
+from numpy.fft import *
+from numpy.random import *
+from numpy.linalg import *
+
+import numpy as np
+import numpy.ma as ma
+
+# don't let numpy's datetime hide stdlib
+import datetime
+
+# This is needed, or bytes will be numpy.random.bytes from
+# "from numpy.random import *" above
+bytes = __import__("builtins").bytes
+# We also don't want the numpy version of these functions
+abs = __import__("builtins").abs
+max = __import__("builtins").max
+min = __import__("builtins").min
+round = __import__("builtins").round
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/quiver.py b/omnilmm/lib/python3.10/site-packages/matplotlib/quiver.py
new file mode 100644
index 0000000000000000000000000000000000000000..46f29420929a91fe2653d6a15455a1120a5b6ec1
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/quiver.py
@@ -0,0 +1,1182 @@
+"""
+Support for plotting vector fields.
+
+Presently this contains Quiver and Barb. Quiver plots an arrow in the
+direction of the vector, with the size of the arrow related to the
+magnitude of the vector.
+
+Barbs are like quiver in that they point along a vector, but
+the magnitude of the vector is given schematically by the presence of barbs
+or flags on the barb.
+
+This will also become a home for things such as standard
+deviation ellipses, which can and will be derived very easily from
+the Quiver code.
+"""
+
+import math
+
+import numpy as np
+from numpy import ma
+
+from matplotlib import _api, cbook, _docstring
+import matplotlib.artist as martist
+import matplotlib.collections as mcollections
+from matplotlib.patches import CirclePolygon
+import matplotlib.text as mtext
+import matplotlib.transforms as transforms
+
+
+_quiver_doc = """
+Plot a 2D field of arrows.
+
+Call signature::
+
+ quiver([X, Y], U, V, [C], **kwargs)
+
+*X*, *Y* define the arrow locations, *U*, *V* define the arrow directions, and
+*C* optionally sets the color.
+
+**Arrow length**
+
+The default settings auto-scales the length of the arrows to a reasonable size.
+To change this behavior see the *scale* and *scale_units* parameters.
+
+**Arrow shape**
+
+The arrow shape is determined by *width*, *headwidth*, *headlength* and
+*headaxislength*. See the notes below.
+
+**Arrow styling**
+
+Each arrow is internally represented by a filled polygon with a default edge
+linewidth of 0. As a result, an arrow is rather a filled area, not a line with
+a head, and `.PolyCollection` properties like *linewidth*, *edgecolor*,
+*facecolor*, etc. act accordingly.
+
+
+Parameters
+----------
+X, Y : 1D or 2D array-like, optional
+ The x and y coordinates of the arrow locations.
+
+ If not given, they will be generated as a uniform integer meshgrid based
+ on the dimensions of *U* and *V*.
+
+ If *X* and *Y* are 1D but *U*, *V* are 2D, *X*, *Y* are expanded to 2D
+ using ``X, Y = np.meshgrid(X, Y)``. In this case ``len(X)`` and ``len(Y)``
+ must match the column and row dimensions of *U* and *V*.
+
+U, V : 1D or 2D array-like
+ The x and y direction components of the arrow vectors. The interpretation
+ of these components (in data or in screen space) depends on *angles*.
+
+ *U* and *V* must have the same number of elements, matching the number of
+ arrow locations in *X*, *Y*. *U* and *V* may be masked. Locations masked
+ in any of *U*, *V*, and *C* will not be drawn.
+
+C : 1D or 2D array-like, optional
+ Numeric data that defines the arrow colors by colormapping via *norm* and
+ *cmap*.
+
+ This does not support explicit colors. If you want to set colors directly,
+ use *color* instead. The size of *C* must match the number of arrow
+ locations.
+
+angles : {'uv', 'xy'} or array-like, default: 'uv'
+ Method for determining the angle of the arrows.
+
+ - 'uv': Arrow direction in screen coordinates. Use this if the arrows
+ symbolize a quantity that is not based on *X*, *Y* data coordinates.
+
+ If *U* == *V* the orientation of the arrow on the plot is 45 degrees
+ counter-clockwise from the horizontal axis (positive to the right).
+
+ - 'xy': Arrow direction in data coordinates, i.e. the arrows point from
+ (x, y) to (x+u, y+v). Use this e.g. for plotting a gradient field.
+
+ - Arbitrary angles may be specified explicitly as an array of values
+ in degrees, counter-clockwise from the horizontal axis.
+
+ In this case *U*, *V* is only used to determine the length of the
+ arrows.
+
+ Note: inverting a data axis will correspondingly invert the
+ arrows only with ``angles='xy'``.
+
+pivot : {'tail', 'mid', 'middle', 'tip'}, default: 'tail'
+ The part of the arrow that is anchored to the *X*, *Y* grid. The arrow
+ rotates about this point.
+
+ 'mid' is a synonym for 'middle'.
+
+scale : float, optional
+ Scales the length of the arrow inversely.
+
+ Number of data units per arrow length unit, e.g., m/s per plot width; a
+ smaller scale parameter makes the arrow longer. Default is *None*.
+
+ If *None*, a simple autoscaling algorithm is used, based on the average
+ vector length and the number of vectors. The arrow length unit is given by
+ the *scale_units* parameter.
+
+scale_units : {'width', 'height', 'dots', 'inches', 'x', 'y', 'xy'}, optional
+ If the *scale* kwarg is *None*, the arrow length unit. Default is *None*.
+
+ e.g. *scale_units* is 'inches', *scale* is 2.0, and ``(u, v) = (1, 0)``,
+ then the vector will be 0.5 inches long.
+
+ If *scale_units* is 'width' or 'height', then the vector will be half the
+ width/height of the axes.
+
+ If *scale_units* is 'x' then the vector will be 0.5 x-axis
+ units. To plot vectors in the x-y plane, with u and v having
+ the same units as x and y, use
+ ``angles='xy', scale_units='xy', scale=1``.
+
+units : {'width', 'height', 'dots', 'inches', 'x', 'y', 'xy'}, default: 'width'
+ Affects the arrow size (except for the length). In particular, the shaft
+ *width* is measured in multiples of this unit.
+
+ Supported values are:
+
+ - 'width', 'height': The width or height of the Axes.
+ - 'dots', 'inches': Pixels or inches based on the figure dpi.
+ - 'x', 'y', 'xy': *X*, *Y* or :math:`\\sqrt{X^2 + Y^2}` in data units.
+
+ The following table summarizes how these values affect the visible arrow
+ size under zooming and figure size changes:
+
+ ================= ================= ==================
+ units zoom figure size change
+ ================= ================= ==================
+ 'x', 'y', 'xy' arrow size scales —
+ 'width', 'height' — arrow size scales
+ 'dots', 'inches' — —
+ ================= ================= ==================
+
+width : float, optional
+ Shaft width in arrow units. All head parameters are relative to *width*.
+
+ The default depends on choice of *units* above, and number of vectors;
+ a typical starting value is about 0.005 times the width of the plot.
+
+headwidth : float, default: 3
+ Head width as multiple of shaft *width*. See the notes below.
+
+headlength : float, default: 5
+ Head length as multiple of shaft *width*. See the notes below.
+
+headaxislength : float, default: 4.5
+ Head length at shaft intersection as multiple of shaft *width*.
+ See the notes below.
+
+minshaft : float, default: 1
+ Length below which arrow scales, in units of head length. Do not
+ set this to less than 1, or small arrows will look terrible!
+
+minlength : float, default: 1
+ Minimum length as a multiple of shaft width; if an arrow length
+ is less than this, plot a dot (hexagon) of this diameter instead.
+
+color : color or color sequence, optional
+ Explicit color(s) for the arrows. If *C* has been set, *color* has no
+ effect.
+
+ This is a synonym for the `.PolyCollection` *facecolor* parameter.
+
+Other Parameters
+----------------
+data : indexable object, optional
+ DATA_PARAMETER_PLACEHOLDER
+
+**kwargs : `~matplotlib.collections.PolyCollection` properties, optional
+ All other keyword arguments are passed on to `.PolyCollection`:
+
+ %(PolyCollection:kwdoc)s
+
+Returns
+-------
+`~matplotlib.quiver.Quiver`
+
+See Also
+--------
+.Axes.quiverkey : Add a key to a quiver plot.
+
+Notes
+-----
+
+**Arrow shape**
+
+The arrow is drawn as a polygon using the nodes as shown below. The values
+*headwidth*, *headlength*, and *headaxislength* are in units of *width*.
+
+.. image:: /_static/quiver_sizes.svg
+ :width: 500px
+
+The defaults give a slightly swept-back arrow. Here are some guidelines how to
+get other head shapes:
+
+- To make the head a triangle, make *headaxislength* the same as *headlength*.
+- To make the arrow more pointed, reduce *headwidth* or increase *headlength*
+ and *headaxislength*.
+- To make the head smaller relative to the shaft, scale down all the head
+ parameters proportionally.
+- To remove the head completely, set all *head* parameters to 0.
+- To get a diamond-shaped head, make *headaxislength* larger than *headlength*.
+- Warning: For *headaxislength* < (*headlength* / *headwidth*), the "headaxis"
+ nodes (i.e. the ones connecting the head with the shaft) will protrude out
+ of the head in forward direction so that the arrow head looks broken.
+""" % _docstring.interpd.params
+
+_docstring.interpd.update(quiver_doc=_quiver_doc)
+
+
+class QuiverKey(martist.Artist):
+ """Labelled arrow for use as a quiver plot scale key."""
+ halign = {'N': 'center', 'S': 'center', 'E': 'left', 'W': 'right'}
+ valign = {'N': 'bottom', 'S': 'top', 'E': 'center', 'W': 'center'}
+ pivot = {'N': 'middle', 'S': 'middle', 'E': 'tip', 'W': 'tail'}
+
+ def __init__(self, Q, X, Y, U, label,
+ *, angle=0, coordinates='axes', color=None, labelsep=0.1,
+ labelpos='N', labelcolor=None, fontproperties=None, **kwargs):
+ """
+ Add a key to a quiver plot.
+
+ The positioning of the key depends on *X*, *Y*, *coordinates*, and
+ *labelpos*. If *labelpos* is 'N' or 'S', *X*, *Y* give the position of
+ the middle of the key arrow. If *labelpos* is 'E', *X*, *Y* positions
+ the head, and if *labelpos* is 'W', *X*, *Y* positions the tail; in
+ either of these two cases, *X*, *Y* is somewhere in the middle of the
+ arrow+label key object.
+
+ Parameters
+ ----------
+ Q : `~matplotlib.quiver.Quiver`
+ A `.Quiver` object as returned by a call to `~.Axes.quiver()`.
+ X, Y : float
+ The location of the key.
+ U : float
+ The length of the key.
+ label : str
+ The key label (e.g., length and units of the key).
+ angle : float, default: 0
+ The angle of the key arrow, in degrees anti-clockwise from the
+ x-axis.
+ coordinates : {'axes', 'figure', 'data', 'inches'}, default: 'axes'
+ Coordinate system and units for *X*, *Y*: 'axes' and 'figure' are
+ normalized coordinate systems with (0, 0) in the lower left and
+ (1, 1) in the upper right; 'data' are the axes data coordinates
+ (used for the locations of the vectors in the quiver plot itself);
+ 'inches' is position in the figure in inches, with (0, 0) at the
+ lower left corner.
+ color : color
+ Overrides face and edge colors from *Q*.
+ labelpos : {'N', 'S', 'E', 'W'}
+ Position the label above, below, to the right, to the left of the
+ arrow, respectively.
+ labelsep : float, default: 0.1
+ Distance in inches between the arrow and the label.
+ labelcolor : color, default: :rc:`text.color`
+ Label color.
+ fontproperties : dict, optional
+ A dictionary with keyword arguments accepted by the
+ `~matplotlib.font_manager.FontProperties` initializer:
+ *family*, *style*, *variant*, *size*, *weight*.
+ **kwargs
+ Any additional keyword arguments are used to override vector
+ properties taken from *Q*.
+ """
+ super().__init__()
+ self.Q = Q
+ self.X = X
+ self.Y = Y
+ self.U = U
+ self.angle = angle
+ self.coord = coordinates
+ self.color = color
+ self.label = label
+ self._labelsep_inches = labelsep
+
+ self.labelpos = labelpos
+ self.labelcolor = labelcolor
+ self.fontproperties = fontproperties or dict()
+ self.kw = kwargs
+ self.text = mtext.Text(
+ text=label,
+ horizontalalignment=self.halign[self.labelpos],
+ verticalalignment=self.valign[self.labelpos],
+ fontproperties=self.fontproperties)
+ if self.labelcolor is not None:
+ self.text.set_color(self.labelcolor)
+ self._dpi_at_last_init = None
+ self.zorder = Q.zorder + 0.1
+
+ @property
+ def labelsep(self):
+ return self._labelsep_inches * self.Q.axes.figure.dpi
+
+ def _init(self):
+ if True: # self._dpi_at_last_init != self.axes.figure.dpi
+ if self.Q._dpi_at_last_init != self.Q.axes.figure.dpi:
+ self.Q._init()
+ self._set_transform()
+ with cbook._setattr_cm(self.Q, pivot=self.pivot[self.labelpos],
+ # Hack: save and restore the Umask
+ Umask=ma.nomask):
+ u = self.U * np.cos(np.radians(self.angle))
+ v = self.U * np.sin(np.radians(self.angle))
+ angle = (self.Q.angles if isinstance(self.Q.angles, str)
+ else 'uv')
+ self.verts = self.Q._make_verts(
+ np.array([u]), np.array([v]), angle)
+ kwargs = self.Q.polykw
+ kwargs.update(self.kw)
+ self.vector = mcollections.PolyCollection(
+ self.verts,
+ offsets=[(self.X, self.Y)],
+ offset_transform=self.get_transform(),
+ **kwargs)
+ if self.color is not None:
+ self.vector.set_color(self.color)
+ self.vector.set_transform(self.Q.get_transform())
+ self.vector.set_figure(self.get_figure())
+ self._dpi_at_last_init = self.Q.axes.figure.dpi
+
+ def _text_shift(self):
+ return {
+ "N": (0, +self.labelsep),
+ "S": (0, -self.labelsep),
+ "E": (+self.labelsep, 0),
+ "W": (-self.labelsep, 0),
+ }[self.labelpos]
+
+ @martist.allow_rasterization
+ def draw(self, renderer):
+ self._init()
+ self.vector.draw(renderer)
+ pos = self.get_transform().transform((self.X, self.Y))
+ self.text.set_position(pos + self._text_shift())
+ self.text.draw(renderer)
+ self.stale = False
+
+ def _set_transform(self):
+ self.set_transform(_api.check_getitem({
+ "data": self.Q.axes.transData,
+ "axes": self.Q.axes.transAxes,
+ "figure": self.Q.axes.figure.transFigure,
+ "inches": self.Q.axes.figure.dpi_scale_trans,
+ }, coordinates=self.coord))
+
+ def set_figure(self, fig):
+ super().set_figure(fig)
+ self.text.set_figure(fig)
+
+ def contains(self, mouseevent):
+ inside, info = self._default_contains(mouseevent)
+ if inside is not None:
+ return inside, info
+ # Maybe the dictionary should allow one to
+ # distinguish between a text hit and a vector hit.
+ if (self.text.contains(mouseevent)[0] or
+ self.vector.contains(mouseevent)[0]):
+ return True, {}
+ return False, {}
+
+
+def _parse_args(*args, caller_name='function'):
+ """
+ Helper function to parse positional parameters for colored vector plots.
+
+ This is currently used for Quiver and Barbs.
+
+ Parameters
+ ----------
+ *args : list
+ list of 2-5 arguments. Depending on their number they are parsed to::
+
+ U, V
+ U, V, C
+ X, Y, U, V
+ X, Y, U, V, C
+
+ caller_name : str
+ Name of the calling method (used in error messages).
+ """
+ X = Y = C = None
+
+ nargs = len(args)
+ if nargs == 2:
+ # The use of atleast_1d allows for handling scalar arguments while also
+ # keeping masked arrays
+ U, V = np.atleast_1d(*args)
+ elif nargs == 3:
+ U, V, C = np.atleast_1d(*args)
+ elif nargs == 4:
+ X, Y, U, V = np.atleast_1d(*args)
+ elif nargs == 5:
+ X, Y, U, V, C = np.atleast_1d(*args)
+ else:
+ raise _api.nargs_error(caller_name, takes="from 2 to 5", given=nargs)
+
+ nr, nc = (1, U.shape[0]) if U.ndim == 1 else U.shape
+
+ if X is not None:
+ X = X.ravel()
+ Y = Y.ravel()
+ if len(X) == nc and len(Y) == nr:
+ X, Y = [a.ravel() for a in np.meshgrid(X, Y)]
+ elif len(X) != len(Y):
+ raise ValueError('X and Y must be the same size, but '
+ f'X.size is {X.size} and Y.size is {Y.size}.')
+ else:
+ indexgrid = np.meshgrid(np.arange(nc), np.arange(nr))
+ X, Y = [np.ravel(a) for a in indexgrid]
+ # Size validation for U, V, C is left to the set_UVC method.
+ return X, Y, U, V, C
+
+
+def _check_consistent_shapes(*arrays):
+ all_shapes = {a.shape for a in arrays}
+ if len(all_shapes) != 1:
+ raise ValueError('The shapes of the passed in arrays do not match')
+
+
+class Quiver(mcollections.PolyCollection):
+ """
+ Specialized PolyCollection for arrows.
+
+ The only API method is set_UVC(), which can be used
+ to change the size, orientation, and color of the
+ arrows; their locations are fixed when the class is
+ instantiated. Possibly this method will be useful
+ in animations.
+
+ Much of the work in this class is done in the draw()
+ method so that as much information as possible is available
+ about the plot. In subsequent draw() calls, recalculation
+ is limited to things that might have changed, so there
+ should be no performance penalty from putting the calculations
+ in the draw() method.
+ """
+
+ _PIVOT_VALS = ('tail', 'middle', 'tip')
+
+ @_docstring.Substitution(_quiver_doc)
+ def __init__(self, ax, *args,
+ scale=None, headwidth=3, headlength=5, headaxislength=4.5,
+ minshaft=1, minlength=1, units='width', scale_units=None,
+ angles='uv', width=None, color='k', pivot='tail', **kwargs):
+ """
+ The constructor takes one required argument, an Axes
+ instance, followed by the args and kwargs described
+ by the following pyplot interface documentation:
+ %s
+ """
+ self._axes = ax # The attr actually set by the Artist.axes property.
+ X, Y, U, V, C = _parse_args(*args, caller_name='quiver')
+ self.X = X
+ self.Y = Y
+ self.XY = np.column_stack((X, Y))
+ self.N = len(X)
+ self.scale = scale
+ self.headwidth = headwidth
+ self.headlength = float(headlength)
+ self.headaxislength = headaxislength
+ self.minshaft = minshaft
+ self.minlength = minlength
+ self.units = units
+ self.scale_units = scale_units
+ self.angles = angles
+ self.width = width
+
+ if pivot.lower() == 'mid':
+ pivot = 'middle'
+ self.pivot = pivot.lower()
+ _api.check_in_list(self._PIVOT_VALS, pivot=self.pivot)
+
+ self.transform = kwargs.pop('transform', ax.transData)
+ kwargs.setdefault('facecolors', color)
+ kwargs.setdefault('linewidths', (0,))
+ super().__init__([], offsets=self.XY, offset_transform=self.transform,
+ closed=False, **kwargs)
+ self.polykw = kwargs
+ self.set_UVC(U, V, C)
+ self._dpi_at_last_init = None
+
+ def _init(self):
+ """
+ Initialization delayed until first draw;
+ allow time for axes setup.
+ """
+ # It seems that there are not enough event notifications
+ # available to have this work on an as-needed basis at present.
+ if True: # self._dpi_at_last_init != self.axes.figure.dpi
+ trans = self._set_transform()
+ self.span = trans.inverted().transform_bbox(self.axes.bbox).width
+ if self.width is None:
+ sn = np.clip(math.sqrt(self.N), 8, 25)
+ self.width = 0.06 * self.span / sn
+
+ # _make_verts sets self.scale if not already specified
+ if (self._dpi_at_last_init != self.axes.figure.dpi
+ and self.scale is None):
+ self._make_verts(self.U, self.V, self.angles)
+
+ self._dpi_at_last_init = self.axes.figure.dpi
+
+ def get_datalim(self, transData):
+ trans = self.get_transform()
+ offset_trf = self.get_offset_transform()
+ full_transform = (trans - transData) + (offset_trf - transData)
+ XY = full_transform.transform(self.XY)
+ bbox = transforms.Bbox.null()
+ bbox.update_from_data_xy(XY, ignore=True)
+ return bbox
+
+ @martist.allow_rasterization
+ def draw(self, renderer):
+ self._init()
+ verts = self._make_verts(self.U, self.V, self.angles)
+ self.set_verts(verts, closed=False)
+ super().draw(renderer)
+ self.stale = False
+
+ def set_UVC(self, U, V, C=None):
+ # We need to ensure we have a copy, not a reference
+ # to an array that might change before draw().
+ U = ma.masked_invalid(U, copy=True).ravel()
+ V = ma.masked_invalid(V, copy=True).ravel()
+ if C is not None:
+ C = ma.masked_invalid(C, copy=True).ravel()
+ for name, var in zip(('U', 'V', 'C'), (U, V, C)):
+ if not (var is None or var.size == self.N or var.size == 1):
+ raise ValueError(f'Argument {name} has a size {var.size}'
+ f' which does not match {self.N},'
+ ' the number of arrow positions')
+
+ mask = ma.mask_or(U.mask, V.mask, copy=False, shrink=True)
+ if C is not None:
+ mask = ma.mask_or(mask, C.mask, copy=False, shrink=True)
+ if mask is ma.nomask:
+ C = C.filled()
+ else:
+ C = ma.array(C, mask=mask, copy=False)
+ self.U = U.filled(1)
+ self.V = V.filled(1)
+ self.Umask = mask
+ if C is not None:
+ self.set_array(C)
+ self.stale = True
+
+ def _dots_per_unit(self, units):
+ """Return a scale factor for converting from units to pixels."""
+ bb = self.axes.bbox
+ vl = self.axes.viewLim
+ return _api.check_getitem({
+ 'x': bb.width / vl.width,
+ 'y': bb.height / vl.height,
+ 'xy': np.hypot(*bb.size) / np.hypot(*vl.size),
+ 'width': bb.width,
+ 'height': bb.height,
+ 'dots': 1.,
+ 'inches': self.axes.figure.dpi,
+ }, units=units)
+
+ def _set_transform(self):
+ """
+ Set the PolyCollection transform to go
+ from arrow width units to pixels.
+ """
+ dx = self._dots_per_unit(self.units)
+ self._trans_scale = dx # pixels per arrow width unit
+ trans = transforms.Affine2D().scale(dx)
+ self.set_transform(trans)
+ return trans
+
+ def _angles_lengths(self, U, V, eps=1):
+ xy = self.axes.transData.transform(self.XY)
+ uv = np.column_stack((U, V))
+ xyp = self.axes.transData.transform(self.XY + eps * uv)
+ dxy = xyp - xy
+ angles = np.arctan2(dxy[:, 1], dxy[:, 0])
+ lengths = np.hypot(*dxy.T) / eps
+ return angles, lengths
+
+ def _make_verts(self, U, V, angles):
+ uv = (U + V * 1j)
+ str_angles = angles if isinstance(angles, str) else ''
+ if str_angles == 'xy' and self.scale_units == 'xy':
+ # Here eps is 1 so that if we get U, V by diffing
+ # the X, Y arrays, the vectors will connect the
+ # points, regardless of the axis scaling (including log).
+ angles, lengths = self._angles_lengths(U, V, eps=1)
+ elif str_angles == 'xy' or self.scale_units == 'xy':
+ # Calculate eps based on the extents of the plot
+ # so that we don't end up with roundoff error from
+ # adding a small number to a large.
+ eps = np.abs(self.axes.dataLim.extents).max() * 0.001
+ angles, lengths = self._angles_lengths(U, V, eps=eps)
+ if str_angles and self.scale_units == 'xy':
+ a = lengths
+ else:
+ a = np.abs(uv)
+ if self.scale is None:
+ sn = max(10, math.sqrt(self.N))
+ if self.Umask is not ma.nomask:
+ amean = a[~self.Umask].mean()
+ else:
+ amean = a.mean()
+ # crude auto-scaling
+ # scale is typical arrow length as a multiple of the arrow width
+ scale = 1.8 * amean * sn / self.span
+ if self.scale_units is None:
+ if self.scale is None:
+ self.scale = scale
+ widthu_per_lenu = 1.0
+ else:
+ if self.scale_units == 'xy':
+ dx = 1
+ else:
+ dx = self._dots_per_unit(self.scale_units)
+ widthu_per_lenu = dx / self._trans_scale
+ if self.scale is None:
+ self.scale = scale * widthu_per_lenu
+ length = a * (widthu_per_lenu / (self.scale * self.width))
+ X, Y = self._h_arrows(length)
+ if str_angles == 'xy':
+ theta = angles
+ elif str_angles == 'uv':
+ theta = np.angle(uv)
+ else:
+ theta = ma.masked_invalid(np.deg2rad(angles)).filled(0)
+ theta = theta.reshape((-1, 1)) # for broadcasting
+ xy = (X + Y * 1j) * np.exp(1j * theta) * self.width
+ XY = np.stack((xy.real, xy.imag), axis=2)
+ if self.Umask is not ma.nomask:
+ XY = ma.array(XY)
+ XY[self.Umask] = ma.masked
+ # This might be handled more efficiently with nans, given
+ # that nans will end up in the paths anyway.
+
+ return XY
+
+ def _h_arrows(self, length):
+ """Length is in arrow width units."""
+ # It might be possible to streamline the code
+ # and speed it up a bit by using complex (x, y)
+ # instead of separate arrays; but any gain would be slight.
+ minsh = self.minshaft * self.headlength
+ N = len(length)
+ length = length.reshape(N, 1)
+ # This number is chosen based on when pixel values overflow in Agg
+ # causing rendering errors
+ # length = np.minimum(length, 2 ** 16)
+ np.clip(length, 0, 2 ** 16, out=length)
+ # x, y: normal horizontal arrow
+ x = np.array([0, -self.headaxislength,
+ -self.headlength, 0],
+ np.float64)
+ x = x + np.array([0, 1, 1, 1]) * length
+ y = 0.5 * np.array([1, 1, self.headwidth, 0], np.float64)
+ y = np.repeat(y[np.newaxis, :], N, axis=0)
+ # x0, y0: arrow without shaft, for short vectors
+ x0 = np.array([0, minsh - self.headaxislength,
+ minsh - self.headlength, minsh], np.float64)
+ y0 = 0.5 * np.array([1, 1, self.headwidth, 0], np.float64)
+ ii = [0, 1, 2, 3, 2, 1, 0, 0]
+ X = x[:, ii]
+ Y = y[:, ii]
+ Y[:, 3:-1] *= -1
+ X0 = x0[ii]
+ Y0 = y0[ii]
+ Y0[3:-1] *= -1
+ shrink = length / minsh if minsh != 0. else 0.
+ X0 = shrink * X0[np.newaxis, :]
+ Y0 = shrink * Y0[np.newaxis, :]
+ short = np.repeat(length < minsh, 8, axis=1)
+ # Now select X0, Y0 if short, otherwise X, Y
+ np.copyto(X, X0, where=short)
+ np.copyto(Y, Y0, where=short)
+ if self.pivot == 'middle':
+ X -= 0.5 * X[:, 3, np.newaxis]
+ elif self.pivot == 'tip':
+ # numpy bug? using -= does not work here unless we multiply by a
+ # float first, as with 'mid'.
+ X = X - X[:, 3, np.newaxis]
+ elif self.pivot != 'tail':
+ _api.check_in_list(["middle", "tip", "tail"], pivot=self.pivot)
+
+ tooshort = length < self.minlength
+ if tooshort.any():
+ # Use a heptagonal dot:
+ th = np.arange(0, 8, 1, np.float64) * (np.pi / 3.0)
+ x1 = np.cos(th) * self.minlength * 0.5
+ y1 = np.sin(th) * self.minlength * 0.5
+ X1 = np.repeat(x1[np.newaxis, :], N, axis=0)
+ Y1 = np.repeat(y1[np.newaxis, :], N, axis=0)
+ tooshort = np.repeat(tooshort, 8, 1)
+ np.copyto(X, X1, where=tooshort)
+ np.copyto(Y, Y1, where=tooshort)
+ # Mask handling is deferred to the caller, _make_verts.
+ return X, Y
+
+ quiver_doc = _api.deprecated("3.7")(property(lambda self: _quiver_doc))
+
+
+_barbs_doc = r"""
+Plot a 2D field of barbs.
+
+Call signature::
+
+ barbs([X, Y], U, V, [C], **kwargs)
+
+Where *X*, *Y* define the barb locations, *U*, *V* define the barb
+directions, and *C* optionally sets the color.
+
+All arguments may be 1D or 2D. *U*, *V*, *C* may be masked arrays, but masked
+*X*, *Y* are not supported at present.
+
+Barbs are traditionally used in meteorology as a way to plot the speed
+and direction of wind observations, but can technically be used to
+plot any two dimensional vector quantity. As opposed to arrows, which
+give vector magnitude by the length of the arrow, the barbs give more
+quantitative information about the vector magnitude by putting slanted
+lines or a triangle for various increments in magnitude, as show
+schematically below::
+
+ : /\ \
+ : / \ \
+ : / \ \ \
+ : / \ \ \
+ : ------------------------------
+
+The largest increment is given by a triangle (or "flag"). After those
+come full lines (barbs). The smallest increment is a half line. There
+is only, of course, ever at most 1 half line. If the magnitude is
+small and only needs a single half-line and no full lines or
+triangles, the half-line is offset from the end of the barb so that it
+can be easily distinguished from barbs with a single full line. The
+magnitude for the barb shown above would nominally be 65, using the
+standard increments of 50, 10, and 5.
+
+See also https://en.wikipedia.org/wiki/Wind_barb.
+
+Parameters
+----------
+X, Y : 1D or 2D array-like, optional
+ The x and y coordinates of the barb locations. See *pivot* for how the
+ barbs are drawn to the x, y positions.
+
+ If not given, they will be generated as a uniform integer meshgrid based
+ on the dimensions of *U* and *V*.
+
+ If *X* and *Y* are 1D but *U*, *V* are 2D, *X*, *Y* are expanded to 2D
+ using ``X, Y = np.meshgrid(X, Y)``. In this case ``len(X)`` and ``len(Y)``
+ must match the column and row dimensions of *U* and *V*.
+
+U, V : 1D or 2D array-like
+ The x and y components of the barb shaft.
+
+C : 1D or 2D array-like, optional
+ Numeric data that defines the barb colors by colormapping via *norm* and
+ *cmap*.
+
+ This does not support explicit colors. If you want to set colors directly,
+ use *barbcolor* instead.
+
+length : float, default: 7
+ Length of the barb in points; the other parts of the barb
+ are scaled against this.
+
+pivot : {'tip', 'middle'} or float, default: 'tip'
+ The part of the arrow that is anchored to the *X*, *Y* grid. The barb
+ rotates about this point. This can also be a number, which shifts the
+ start of the barb that many points away from grid point.
+
+barbcolor : color or color sequence
+ The color of all parts of the barb except for the flags. This parameter
+ is analogous to the *edgecolor* parameter for polygons, which can be used
+ instead. However this parameter will override facecolor.
+
+flagcolor : color or color sequence
+ The color of any flags on the barb. This parameter is analogous to the
+ *facecolor* parameter for polygons, which can be used instead. However,
+ this parameter will override facecolor. If this is not set (and *C* has
+ not either) then *flagcolor* will be set to match *barbcolor* so that the
+ barb has a uniform color. If *C* has been set, *flagcolor* has no effect.
+
+sizes : dict, optional
+ A dictionary of coefficients specifying the ratio of a given
+ feature to the length of the barb. Only those values one wishes to
+ override need to be included. These features include:
+
+ - 'spacing' - space between features (flags, full/half barbs)
+ - 'height' - height (distance from shaft to top) of a flag or full barb
+ - 'width' - width of a flag, twice the width of a full barb
+ - 'emptybarb' - radius of the circle used for low magnitudes
+
+fill_empty : bool, default: False
+ Whether the empty barbs (circles) that are drawn should be filled with
+ the flag color. If they are not filled, the center is transparent.
+
+rounding : bool, default: True
+ Whether the vector magnitude should be rounded when allocating barb
+ components. If True, the magnitude is rounded to the nearest multiple
+ of the half-barb increment. If False, the magnitude is simply truncated
+ to the next lowest multiple.
+
+barb_increments : dict, optional
+ A dictionary of increments specifying values to associate with
+ different parts of the barb. Only those values one wishes to
+ override need to be included.
+
+ - 'half' - half barbs (Default is 5)
+ - 'full' - full barbs (Default is 10)
+ - 'flag' - flags (default is 50)
+
+flip_barb : bool or array-like of bool, default: False
+ Whether the lines and flags should point opposite to normal.
+ Normal behavior is for the barbs and lines to point right (comes from wind
+ barbs having these features point towards low pressure in the Northern
+ Hemisphere).
+
+ A single value is applied to all barbs. Individual barbs can be flipped by
+ passing a bool array of the same size as *U* and *V*.
+
+Returns
+-------
+barbs : `~matplotlib.quiver.Barbs`
+
+Other Parameters
+----------------
+data : indexable object, optional
+ DATA_PARAMETER_PLACEHOLDER
+
+**kwargs
+ The barbs can further be customized using `.PolyCollection` keyword
+ arguments:
+
+ %(PolyCollection:kwdoc)s
+""" % _docstring.interpd.params
+
+_docstring.interpd.update(barbs_doc=_barbs_doc)
+
+
+class Barbs(mcollections.PolyCollection):
+ """
+ Specialized PolyCollection for barbs.
+
+ The only API method is :meth:`set_UVC`, which can be used to
+ change the size, orientation, and color of the arrows. Locations
+ are changed using the :meth:`set_offsets` collection method.
+ Possibly this method will be useful in animations.
+
+ There is one internal function :meth:`_find_tails` which finds
+ exactly what should be put on the barb given the vector magnitude.
+ From there :meth:`_make_barbs` is used to find the vertices of the
+ polygon to represent the barb based on this information.
+ """
+
+ # This may be an abuse of polygons here to render what is essentially maybe
+ # 1 triangle and a series of lines. It works fine as far as I can tell
+ # however.
+
+ @_docstring.interpd
+ def __init__(self, ax, *args,
+ pivot='tip', length=7, barbcolor=None, flagcolor=None,
+ sizes=None, fill_empty=False, barb_increments=None,
+ rounding=True, flip_barb=False, **kwargs):
+ """
+ The constructor takes one required argument, an Axes
+ instance, followed by the args and kwargs described
+ by the following pyplot interface documentation:
+ %(barbs_doc)s
+ """
+ self.sizes = sizes or dict()
+ self.fill_empty = fill_empty
+ self.barb_increments = barb_increments or dict()
+ self.rounding = rounding
+ self.flip = np.atleast_1d(flip_barb)
+ transform = kwargs.pop('transform', ax.transData)
+ self._pivot = pivot
+ self._length = length
+
+ # Flagcolor and barbcolor provide convenience parameters for
+ # setting the facecolor and edgecolor, respectively, of the barb
+ # polygon. We also work here to make the flag the same color as the
+ # rest of the barb by default
+
+ if None in (barbcolor, flagcolor):
+ kwargs['edgecolors'] = 'face'
+ if flagcolor:
+ kwargs['facecolors'] = flagcolor
+ elif barbcolor:
+ kwargs['facecolors'] = barbcolor
+ else:
+ # Set to facecolor passed in or default to black
+ kwargs.setdefault('facecolors', 'k')
+ else:
+ kwargs['edgecolors'] = barbcolor
+ kwargs['facecolors'] = flagcolor
+
+ # Explicitly set a line width if we're not given one, otherwise
+ # polygons are not outlined and we get no barbs
+ if 'linewidth' not in kwargs and 'lw' not in kwargs:
+ kwargs['linewidth'] = 1
+
+ # Parse out the data arrays from the various configurations supported
+ x, y, u, v, c = _parse_args(*args, caller_name='barbs')
+ self.x = x
+ self.y = y
+ xy = np.column_stack((x, y))
+
+ # Make a collection
+ barb_size = self._length ** 2 / 4 # Empirically determined
+ super().__init__(
+ [], (barb_size,), offsets=xy, offset_transform=transform, **kwargs)
+ self.set_transform(transforms.IdentityTransform())
+
+ self.set_UVC(u, v, c)
+
+ def _find_tails(self, mag, rounding=True, half=5, full=10, flag=50):
+ """
+ Find how many of each of the tail pieces is necessary.
+
+ Parameters
+ ----------
+ mag : `~numpy.ndarray`
+ Vector magnitudes; must be non-negative (and an actual ndarray).
+ rounding : bool, default: True
+ Whether to round or to truncate to the nearest half-barb.
+ half, full, flag : float, defaults: 5, 10, 50
+ Increments for a half-barb, a barb, and a flag.
+
+ Returns
+ -------
+ n_flags, n_barbs : int array
+ For each entry in *mag*, the number of flags and barbs.
+ half_flag : bool array
+ For each entry in *mag*, whether a half-barb is needed.
+ empty_flag : bool array
+ For each entry in *mag*, whether nothing is drawn.
+ """
+ # If rounding, round to the nearest multiple of half, the smallest
+ # increment
+ if rounding:
+ mag = half * np.around(mag / half)
+ n_flags, mag = divmod(mag, flag)
+ n_barb, mag = divmod(mag, full)
+ half_flag = mag >= half
+ empty_flag = ~(half_flag | (n_flags > 0) | (n_barb > 0))
+ return n_flags.astype(int), n_barb.astype(int), half_flag, empty_flag
+
+ def _make_barbs(self, u, v, nflags, nbarbs, half_barb, empty_flag, length,
+ pivot, sizes, fill_empty, flip):
+ """
+ Create the wind barbs.
+
+ Parameters
+ ----------
+ u, v
+ Components of the vector in the x and y directions, respectively.
+
+ nflags, nbarbs, half_barb, empty_flag
+ Respectively, the number of flags, number of barbs, flag for
+ half a barb, and flag for empty barb, ostensibly obtained from
+ :meth:`_find_tails`.
+
+ length
+ The length of the barb staff in points.
+
+ pivot : {"tip", "middle"} or number
+ The point on the barb around which the entire barb should be
+ rotated. If a number, the start of the barb is shifted by that
+ many points from the origin.
+
+ sizes : dict
+ Coefficients specifying the ratio of a given feature to the length
+ of the barb. These features include:
+
+ - *spacing*: space between features (flags, full/half barbs).
+ - *height*: distance from shaft of top of a flag or full barb.
+ - *width*: width of a flag, twice the width of a full barb.
+ - *emptybarb*: radius of the circle used for low magnitudes.
+
+ fill_empty : bool
+ Whether the circle representing an empty barb should be filled or
+ not (this changes the drawing of the polygon).
+
+ flip : list of bool
+ Whether the features should be flipped to the other side of the
+ barb (useful for winds in the southern hemisphere).
+
+ Returns
+ -------
+ list of arrays of vertices
+ Polygon vertices for each of the wind barbs. These polygons have
+ been rotated to properly align with the vector direction.
+ """
+
+ # These control the spacing and size of barb elements relative to the
+ # length of the shaft
+ spacing = length * sizes.get('spacing', 0.125)
+ full_height = length * sizes.get('height', 0.4)
+ full_width = length * sizes.get('width', 0.25)
+ empty_rad = length * sizes.get('emptybarb', 0.15)
+
+ # Controls y point where to pivot the barb.
+ pivot_points = dict(tip=0.0, middle=-length / 2.)
+
+ endx = 0.0
+ try:
+ endy = float(pivot)
+ except ValueError:
+ endy = pivot_points[pivot.lower()]
+
+ # Get the appropriate angle for the vector components. The offset is
+ # due to the way the barb is initially drawn, going down the y-axis.
+ # This makes sense in a meteorological mode of thinking since there 0
+ # degrees corresponds to north (the y-axis traditionally)
+ angles = -(ma.arctan2(v, u) + np.pi / 2)
+
+ # Used for low magnitude. We just get the vertices, so if we make it
+ # out here, it can be reused. The center set here should put the
+ # center of the circle at the location(offset), rather than at the
+ # same point as the barb pivot; this seems more sensible.
+ circ = CirclePolygon((0, 0), radius=empty_rad).get_verts()
+ if fill_empty:
+ empty_barb = circ
+ else:
+ # If we don't want the empty one filled, we make a degenerate
+ # polygon that wraps back over itself
+ empty_barb = np.concatenate((circ, circ[::-1]))
+
+ barb_list = []
+ for index, angle in np.ndenumerate(angles):
+ # If the vector magnitude is too weak to draw anything, plot an
+ # empty circle instead
+ if empty_flag[index]:
+ # We can skip the transform since the circle has no preferred
+ # orientation
+ barb_list.append(empty_barb)
+ continue
+
+ poly_verts = [(endx, endy)]
+ offset = length
+
+ # Handle if this barb should be flipped
+ barb_height = -full_height if flip[index] else full_height
+
+ # Add vertices for each flag
+ for i in range(nflags[index]):
+ # The spacing that works for the barbs is a little to much for
+ # the flags, but this only occurs when we have more than 1
+ # flag.
+ if offset != length:
+ offset += spacing / 2.
+ poly_verts.extend(
+ [[endx, endy + offset],
+ [endx + barb_height, endy - full_width / 2 + offset],
+ [endx, endy - full_width + offset]])
+
+ offset -= full_width + spacing
+
+ # Add vertices for each barb. These really are lines, but works
+ # great adding 3 vertices that basically pull the polygon out and
+ # back down the line
+ for i in range(nbarbs[index]):
+ poly_verts.extend(
+ [(endx, endy + offset),
+ (endx + barb_height, endy + offset + full_width / 2),
+ (endx, endy + offset)])
+
+ offset -= spacing
+
+ # Add the vertices for half a barb, if needed
+ if half_barb[index]:
+ # If the half barb is the first on the staff, traditionally it
+ # is offset from the end to make it easy to distinguish from a
+ # barb with a full one
+ if offset == length:
+ poly_verts.append((endx, endy + offset))
+ offset -= 1.5 * spacing
+ poly_verts.extend(
+ [(endx, endy + offset),
+ (endx + barb_height / 2, endy + offset + full_width / 4),
+ (endx, endy + offset)])
+
+ # Rotate the barb according the angle. Making the barb first and
+ # then rotating it made the math for drawing the barb really easy.
+ # Also, the transform framework makes doing the rotation simple.
+ poly_verts = transforms.Affine2D().rotate(-angle).transform(
+ poly_verts)
+ barb_list.append(poly_verts)
+
+ return barb_list
+
+ def set_UVC(self, U, V, C=None):
+ # We need to ensure we have a copy, not a reference to an array that
+ # might change before draw().
+ self.u = ma.masked_invalid(U, copy=True).ravel()
+ self.v = ma.masked_invalid(V, copy=True).ravel()
+
+ # Flip needs to have the same number of entries as everything else.
+ # Use broadcast_to to avoid a bloated array of identical values.
+ # (can't rely on actual broadcasting)
+ if len(self.flip) == 1:
+ flip = np.broadcast_to(self.flip, self.u.shape)
+ else:
+ flip = self.flip
+
+ if C is not None:
+ c = ma.masked_invalid(C, copy=True).ravel()
+ x, y, u, v, c, flip = cbook.delete_masked_points(
+ self.x.ravel(), self.y.ravel(), self.u, self.v, c,
+ flip.ravel())
+ _check_consistent_shapes(x, y, u, v, c, flip)
+ else:
+ x, y, u, v, flip = cbook.delete_masked_points(
+ self.x.ravel(), self.y.ravel(), self.u, self.v, flip.ravel())
+ _check_consistent_shapes(x, y, u, v, flip)
+
+ magnitude = np.hypot(u, v)
+ flags, barbs, halves, empty = self._find_tails(
+ magnitude, self.rounding, **self.barb_increments)
+
+ # Get the vertices for each of the barbs
+
+ plot_barbs = self._make_barbs(u, v, flags, barbs, halves, empty,
+ self._length, self._pivot, self.sizes,
+ self.fill_empty, flip)
+ self.set_verts(plot_barbs)
+
+ # Set the color array
+ if C is not None:
+ self.set_array(c)
+
+ # Update the offsets in case the masked data changed
+ xy = np.column_stack((x, y))
+ self._offsets = xy
+ self.stale = True
+
+ def set_offsets(self, xy):
+ """
+ Set the offsets for the barb polygons. This saves the offsets passed
+ in and masks them as appropriate for the existing U/V data.
+
+ Parameters
+ ----------
+ xy : sequence of pairs of floats
+ """
+ self.x = xy[:, 0]
+ self.y = xy[:, 1]
+ x, y, u, v = cbook.delete_masked_points(
+ self.x.ravel(), self.y.ravel(), self.u, self.v)
+ _check_consistent_shapes(x, y, u, v)
+ xy = np.column_stack((x, y))
+ super().set_offsets(xy)
+ self.stale = True
+
+ barbs_doc = _api.deprecated("3.7")(property(lambda self: _barbs_doc))
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/rcsetup.py b/omnilmm/lib/python3.10/site-packages/matplotlib/rcsetup.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fafd354b15aa5a622287eeb8fc7ed4ced9d05ea
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/rcsetup.py
@@ -0,0 +1,1267 @@
+"""
+The rcsetup module contains the validation code for customization using
+Matplotlib's rc settings.
+
+Each rc setting is assigned a function used to validate any attempted changes
+to that setting. The validation functions are defined in the rcsetup module,
+and are used to construct the rcParams global object which stores the settings
+and is referenced throughout Matplotlib.
+
+The default values of the rc settings are set in the default matplotlibrc file.
+Any additions or deletions to the parameter set listed here should also be
+propagated to the :file:`lib/matplotlib/mpl-data/matplotlibrc` in Matplotlib's
+root source directory.
+"""
+
+import ast
+from functools import lru_cache, reduce
+from numbers import Number
+import operator
+import os
+import re
+
+import numpy as np
+
+from matplotlib import _api, cbook
+from matplotlib.cbook import ls_mapper
+from matplotlib.colors import Colormap, is_color_like
+from matplotlib._fontconfig_pattern import parse_fontconfig_pattern
+from matplotlib._enums import JoinStyle, CapStyle
+
+# Don't let the original cycler collide with our validating cycler
+from cycler import Cycler, cycler as ccycler
+
+
+# The capitalized forms are needed for ipython at present; this may
+# change for later versions.
+interactive_bk = [
+ 'GTK3Agg', 'GTK3Cairo', 'GTK4Agg', 'GTK4Cairo',
+ 'MacOSX',
+ 'nbAgg',
+ 'QtAgg', 'QtCairo', 'Qt5Agg', 'Qt5Cairo',
+ 'TkAgg', 'TkCairo',
+ 'WebAgg',
+ 'WX', 'WXAgg', 'WXCairo',
+]
+non_interactive_bk = ['agg', 'cairo',
+ 'pdf', 'pgf', 'ps', 'svg', 'template']
+all_backends = interactive_bk + non_interactive_bk
+
+
+class ValidateInStrings:
+ def __init__(self, key, valid, ignorecase=False, *,
+ _deprecated_since=None):
+ """*valid* is a list of legal strings."""
+ self.key = key
+ self.ignorecase = ignorecase
+ self._deprecated_since = _deprecated_since
+
+ def func(s):
+ if ignorecase:
+ return s.lower()
+ else:
+ return s
+ self.valid = {func(k): k for k in valid}
+
+ def __call__(self, s):
+ if self._deprecated_since:
+ name, = (k for k, v in globals().items() if v is self)
+ _api.warn_deprecated(
+ self._deprecated_since, name=name, obj_type="function")
+ if self.ignorecase and isinstance(s, str):
+ s = s.lower()
+ if s in self.valid:
+ return self.valid[s]
+ msg = (f"{s!r} is not a valid value for {self.key}; supported values "
+ f"are {[*self.valid.values()]}")
+ if (isinstance(s, str)
+ and (s.startswith('"') and s.endswith('"')
+ or s.startswith("'") and s.endswith("'"))
+ and s[1:-1] in self.valid):
+ msg += "; remove quotes surrounding your string"
+ raise ValueError(msg)
+
+
+@lru_cache()
+def _listify_validator(scalar_validator, allow_stringlist=False, *,
+ n=None, doc=None):
+ def f(s):
+ if isinstance(s, str):
+ try:
+ val = [scalar_validator(v.strip()) for v in s.split(',')
+ if v.strip()]
+ except Exception:
+ if allow_stringlist:
+ # Sometimes, a list of colors might be a single string
+ # of single-letter colornames. So give that a shot.
+ val = [scalar_validator(v.strip()) for v in s if v.strip()]
+ else:
+ raise
+ # Allow any ordered sequence type -- generators, np.ndarray, pd.Series
+ # -- but not sets, whose iteration order is non-deterministic.
+ elif np.iterable(s) and not isinstance(s, (set, frozenset)):
+ # The condition on this list comprehension will preserve the
+ # behavior of filtering out any empty strings (behavior was
+ # from the original validate_stringlist()), while allowing
+ # any non-string/text scalar values such as numbers and arrays.
+ val = [scalar_validator(v) for v in s
+ if not isinstance(v, str) or v]
+ else:
+ raise ValueError(
+ f"Expected str or other non-set iterable, but got {s}")
+ if n is not None and len(val) != n:
+ raise ValueError(
+ f"Expected {n} values, but there are {len(val)} values in {s}")
+ return val
+
+ try:
+ f.__name__ = "{}list".format(scalar_validator.__name__)
+ except AttributeError: # class instance.
+ f.__name__ = "{}List".format(type(scalar_validator).__name__)
+ f.__qualname__ = f.__qualname__.rsplit(".", 1)[0] + "." + f.__name__
+ f.__doc__ = doc if doc is not None else scalar_validator.__doc__
+ return f
+
+
+def validate_any(s):
+ return s
+validate_anylist = _listify_validator(validate_any)
+
+
+def _validate_date(s):
+ try:
+ np.datetime64(s)
+ return s
+ except ValueError:
+ raise ValueError(
+ f'{s!r} should be a string that can be parsed by numpy.datetime64')
+
+
+def validate_bool(b):
+ """Convert b to ``bool`` or raise."""
+ if isinstance(b, str):
+ b = b.lower()
+ if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True):
+ return True
+ elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False):
+ return False
+ else:
+ raise ValueError(f'Cannot convert {b!r} to bool')
+
+
+def validate_axisbelow(s):
+ try:
+ return validate_bool(s)
+ except ValueError:
+ if isinstance(s, str):
+ if s == 'line':
+ return 'line'
+ raise ValueError(f'{s!r} cannot be interpreted as'
+ ' True, False, or "line"')
+
+
+def validate_dpi(s):
+ """Confirm s is string 'figure' or convert s to float or raise."""
+ if s == 'figure':
+ return s
+ try:
+ return float(s)
+ except ValueError as e:
+ raise ValueError(f'{s!r} is not string "figure" and '
+ f'could not convert {s!r} to float') from e
+
+
+def _make_type_validator(cls, *, allow_none=False):
+ """
+ Return a validator that converts inputs to *cls* or raises (and possibly
+ allows ``None`` as well).
+ """
+
+ def validator(s):
+ if (allow_none and
+ (s is None or isinstance(s, str) and s.lower() == "none")):
+ return None
+ if cls is str and not isinstance(s, str):
+ raise ValueError(f'Could not convert {s!r} to str')
+ try:
+ return cls(s)
+ except (TypeError, ValueError) as e:
+ raise ValueError(
+ f'Could not convert {s!r} to {cls.__name__}') from e
+
+ validator.__name__ = f"validate_{cls.__name__}"
+ if allow_none:
+ validator.__name__ += "_or_None"
+ validator.__qualname__ = (
+ validator.__qualname__.rsplit(".", 1)[0] + "." + validator.__name__)
+ return validator
+
+
+validate_string = _make_type_validator(str)
+validate_string_or_None = _make_type_validator(str, allow_none=True)
+validate_stringlist = _listify_validator(
+ validate_string, doc='return a list of strings')
+validate_int = _make_type_validator(int)
+validate_int_or_None = _make_type_validator(int, allow_none=True)
+validate_float = _make_type_validator(float)
+validate_float_or_None = _make_type_validator(float, allow_none=True)
+validate_floatlist = _listify_validator(
+ validate_float, doc='return a list of floats')
+
+
+def _validate_pathlike(s):
+ if isinstance(s, (str, os.PathLike)):
+ # Store value as str because savefig.directory needs to distinguish
+ # between "" (cwd) and "." (cwd, but gets updated by user selections).
+ return os.fsdecode(s)
+ else:
+ return validate_string(s)
+
+
+def validate_fonttype(s):
+ """
+ Confirm that this is a Postscript or PDF font type that we know how to
+ convert to.
+ """
+ fonttypes = {'type3': 3,
+ 'truetype': 42}
+ try:
+ fonttype = validate_int(s)
+ except ValueError:
+ try:
+ return fonttypes[s.lower()]
+ except KeyError as e:
+ raise ValueError('Supported Postscript/PDF font types are %s'
+ % list(fonttypes)) from e
+ else:
+ if fonttype not in fonttypes.values():
+ raise ValueError(
+ 'Supported Postscript/PDF font types are %s' %
+ list(fonttypes.values()))
+ return fonttype
+
+
+_validate_standard_backends = ValidateInStrings(
+ 'backend', all_backends, ignorecase=True)
+_auto_backend_sentinel = object()
+
+
+def validate_backend(s):
+ backend = (
+ s if s is _auto_backend_sentinel or s.startswith("module://")
+ else _validate_standard_backends(s))
+ return backend
+
+
+def _validate_toolbar(s):
+ s = ValidateInStrings(
+ 'toolbar', ['None', 'toolbar2', 'toolmanager'], ignorecase=True)(s)
+ if s == 'toolmanager':
+ _api.warn_external(
+ "Treat the new Tool classes introduced in v1.5 as experimental "
+ "for now; the API and rcParam may change in future versions.")
+ return s
+
+
+def validate_color_or_inherit(s):
+ """Return a valid color arg."""
+ if cbook._str_equal(s, 'inherit'):
+ return s
+ return validate_color(s)
+
+
+def validate_color_or_auto(s):
+ if cbook._str_equal(s, 'auto'):
+ return s
+ return validate_color(s)
+
+
+def validate_color_for_prop_cycle(s):
+ # N-th color cycle syntax can't go into the color cycle.
+ if isinstance(s, str) and re.match("^C[0-9]$", s):
+ raise ValueError(f"Cannot put cycle reference ({s!r}) in prop_cycler")
+ return validate_color(s)
+
+
+def _validate_color_or_linecolor(s):
+ if cbook._str_equal(s, 'linecolor'):
+ return s
+ elif cbook._str_equal(s, 'mfc') or cbook._str_equal(s, 'markerfacecolor'):
+ return 'markerfacecolor'
+ elif cbook._str_equal(s, 'mec') or cbook._str_equal(s, 'markeredgecolor'):
+ return 'markeredgecolor'
+ elif s is None:
+ return None
+ elif isinstance(s, str) and len(s) == 6 or len(s) == 8:
+ stmp = '#' + s
+ if is_color_like(stmp):
+ return stmp
+ if s.lower() == 'none':
+ return None
+ elif is_color_like(s):
+ return s
+
+ raise ValueError(f'{s!r} does not look like a color arg')
+
+
+def validate_color(s):
+ """Return a valid color arg."""
+ if isinstance(s, str):
+ if s.lower() == 'none':
+ return 'none'
+ if len(s) == 6 or len(s) == 8:
+ stmp = '#' + s
+ if is_color_like(stmp):
+ return stmp
+
+ if is_color_like(s):
+ return s
+
+ # If it is still valid, it must be a tuple (as a string from matplotlibrc).
+ try:
+ color = ast.literal_eval(s)
+ except (SyntaxError, ValueError):
+ pass
+ else:
+ if is_color_like(color):
+ return color
+
+ raise ValueError(f'{s!r} does not look like a color arg')
+
+
+validate_colorlist = _listify_validator(
+ validate_color, allow_stringlist=True, doc='return a list of colorspecs')
+
+
+def _validate_cmap(s):
+ _api.check_isinstance((str, Colormap), cmap=s)
+ return s
+
+
+def validate_aspect(s):
+ if s in ('auto', 'equal'):
+ return s
+ try:
+ return float(s)
+ except ValueError as e:
+ raise ValueError('not a valid aspect specification') from e
+
+
+def validate_fontsize_None(s):
+ if s is None or s == 'None':
+ return None
+ else:
+ return validate_fontsize(s)
+
+
+def validate_fontsize(s):
+ fontsizes = ['xx-small', 'x-small', 'small', 'medium', 'large',
+ 'x-large', 'xx-large', 'smaller', 'larger']
+ if isinstance(s, str):
+ s = s.lower()
+ if s in fontsizes:
+ return s
+ try:
+ return float(s)
+ except ValueError as e:
+ raise ValueError("%s is not a valid font size. Valid font sizes "
+ "are %s." % (s, ", ".join(fontsizes))) from e
+
+
+validate_fontsizelist = _listify_validator(validate_fontsize)
+
+
+def validate_fontweight(s):
+ weights = [
+ 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman',
+ 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black']
+ # Note: Historically, weights have been case-sensitive in Matplotlib
+ if s in weights:
+ return s
+ try:
+ return int(s)
+ except (ValueError, TypeError) as e:
+ raise ValueError(f'{s} is not a valid font weight.') from e
+
+
+def validate_fontstretch(s):
+ stretchvalues = [
+ 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed',
+ 'normal', 'semi-expanded', 'expanded', 'extra-expanded',
+ 'ultra-expanded']
+ # Note: Historically, stretchvalues have been case-sensitive in Matplotlib
+ if s in stretchvalues:
+ return s
+ try:
+ return int(s)
+ except (ValueError, TypeError) as e:
+ raise ValueError(f'{s} is not a valid font stretch.') from e
+
+
+def validate_font_properties(s):
+ parse_fontconfig_pattern(s)
+ return s
+
+
+def _validate_mathtext_fallback(s):
+ _fallback_fonts = ['cm', 'stix', 'stixsans']
+ if isinstance(s, str):
+ s = s.lower()
+ if s is None or s == 'none':
+ return None
+ elif s.lower() in _fallback_fonts:
+ return s
+ else:
+ raise ValueError(
+ f"{s} is not a valid fallback font name. Valid fallback font "
+ f"names are {','.join(_fallback_fonts)}. Passing 'None' will turn "
+ "fallback off.")
+
+
+def validate_whiskers(s):
+ try:
+ return _listify_validator(validate_float, n=2)(s)
+ except (TypeError, ValueError):
+ try:
+ return float(s)
+ except ValueError as e:
+ raise ValueError("Not a valid whisker value [float, "
+ "(float, float)]") from e
+
+
+def validate_ps_distiller(s):
+ if isinstance(s, str):
+ s = s.lower()
+ if s in ('none', None, 'false', False):
+ return None
+ else:
+ return ValidateInStrings('ps.usedistiller', ['ghostscript', 'xpdf'])(s)
+
+
+# A validator dedicated to the named line styles, based on the items in
+# ls_mapper, and a list of possible strings read from Line2D.set_linestyle
+_validate_named_linestyle = ValidateInStrings(
+ 'linestyle',
+ [*ls_mapper.keys(), *ls_mapper.values(), 'None', 'none', ' ', ''],
+ ignorecase=True)
+
+
+def _validate_linestyle(ls):
+ """
+ A validator for all possible line styles, the named ones *and*
+ the on-off ink sequences.
+ """
+ if isinstance(ls, str):
+ try: # Look first for a valid named line style, like '--' or 'solid'.
+ return _validate_named_linestyle(ls)
+ except ValueError:
+ pass
+ try:
+ ls = ast.literal_eval(ls) # Parsing matplotlibrc.
+ except (SyntaxError, ValueError):
+ pass # Will error with the ValueError at the end.
+
+ def _is_iterable_not_string_like(x):
+ # Explicitly exclude bytes/bytearrays so that they are not
+ # nonsensically interpreted as sequences of numbers (codepoints).
+ return np.iterable(x) and not isinstance(x, (str, bytes, bytearray))
+
+ if _is_iterable_not_string_like(ls):
+ if len(ls) == 2 and _is_iterable_not_string_like(ls[1]):
+ # (offset, (on, off, on, off, ...))
+ offset, onoff = ls
+ else:
+ # For backcompat: (on, off, on, off, ...); the offset is implicit.
+ offset = 0
+ onoff = ls
+
+ if (isinstance(offset, Number)
+ and len(onoff) % 2 == 0
+ and all(isinstance(elem, Number) for elem in onoff)):
+ return (offset, onoff)
+
+ raise ValueError(f"linestyle {ls!r} is not a valid on-off ink sequence.")
+
+
+validate_fillstyle = ValidateInStrings(
+ 'markers.fillstyle', ['full', 'left', 'right', 'bottom', 'top', 'none'])
+
+
+validate_fillstylelist = _listify_validator(validate_fillstyle)
+
+
+def validate_markevery(s):
+ """
+ Validate the markevery property of a Line2D object.
+
+ Parameters
+ ----------
+ s : None, int, (int, int), slice, float, (float, float), or list[int]
+
+ Returns
+ -------
+ None, int, (int, int), slice, float, (float, float), or list[int]
+ """
+ # Validate s against type slice float int and None
+ if isinstance(s, (slice, float, int, type(None))):
+ return s
+ # Validate s against type tuple
+ if isinstance(s, tuple):
+ if (len(s) == 2
+ and (all(isinstance(e, int) for e in s)
+ or all(isinstance(e, float) for e in s))):
+ return s
+ else:
+ raise TypeError(
+ "'markevery' tuple must be pair of ints or of floats")
+ # Validate s against type list
+ if isinstance(s, list):
+ if all(isinstance(e, int) for e in s):
+ return s
+ else:
+ raise TypeError(
+ "'markevery' list must have all elements of type int")
+ raise TypeError("'markevery' is of an invalid type")
+
+
+validate_markeverylist = _listify_validator(validate_markevery)
+
+
+def validate_bbox(s):
+ if isinstance(s, str):
+ s = s.lower()
+ if s == 'tight':
+ return s
+ if s == 'standard':
+ return None
+ raise ValueError("bbox should be 'tight' or 'standard'")
+ elif s is not None:
+ # Backwards compatibility. None is equivalent to 'standard'.
+ raise ValueError("bbox should be 'tight' or 'standard'")
+ return s
+
+
+def validate_sketch(s):
+ if isinstance(s, str):
+ s = s.lower()
+ if s == 'none' or s is None:
+ return None
+ try:
+ return tuple(_listify_validator(validate_float, n=3)(s))
+ except ValueError:
+ raise ValueError("Expected a (scale, length, randomness) triplet")
+
+
+def _validate_greaterequal0_lessthan1(s):
+ s = validate_float(s)
+ if 0 <= s < 1:
+ return s
+ else:
+ raise RuntimeError(f'Value must be >=0 and <1; got {s}')
+
+
+def _validate_greaterequal0_lessequal1(s):
+ s = validate_float(s)
+ if 0 <= s <= 1:
+ return s
+ else:
+ raise RuntimeError(f'Value must be >=0 and <=1; got {s}')
+
+
+_range_validators = { # Slightly nicer (internal) API.
+ "0 <= x < 1": _validate_greaterequal0_lessthan1,
+ "0 <= x <= 1": _validate_greaterequal0_lessequal1,
+}
+
+
+def validate_hatch(s):
+ r"""
+ Validate a hatch pattern.
+ A hatch pattern string can have any sequence of the following
+ characters: ``\ / | - + * . x o O``.
+ """
+ if not isinstance(s, str):
+ raise ValueError("Hatch pattern must be a string")
+ _api.check_isinstance(str, hatch_pattern=s)
+ unknown = set(s) - {'\\', '/', '|', '-', '+', '*', '.', 'x', 'o', 'O'}
+ if unknown:
+ raise ValueError("Unknown hatch symbol(s): %s" % list(unknown))
+ return s
+
+
+validate_hatchlist = _listify_validator(validate_hatch)
+validate_dashlist = _listify_validator(validate_floatlist)
+
+
+_prop_validators = {
+ 'color': _listify_validator(validate_color_for_prop_cycle,
+ allow_stringlist=True),
+ 'linewidth': validate_floatlist,
+ 'linestyle': _listify_validator(_validate_linestyle),
+ 'facecolor': validate_colorlist,
+ 'edgecolor': validate_colorlist,
+ 'joinstyle': _listify_validator(JoinStyle),
+ 'capstyle': _listify_validator(CapStyle),
+ 'fillstyle': validate_fillstylelist,
+ 'markerfacecolor': validate_colorlist,
+ 'markersize': validate_floatlist,
+ 'markeredgewidth': validate_floatlist,
+ 'markeredgecolor': validate_colorlist,
+ 'markevery': validate_markeverylist,
+ 'alpha': validate_floatlist,
+ 'marker': validate_stringlist,
+ 'hatch': validate_hatchlist,
+ 'dashes': validate_dashlist,
+ }
+_prop_aliases = {
+ 'c': 'color',
+ 'lw': 'linewidth',
+ 'ls': 'linestyle',
+ 'fc': 'facecolor',
+ 'ec': 'edgecolor',
+ 'mfc': 'markerfacecolor',
+ 'mec': 'markeredgecolor',
+ 'mew': 'markeredgewidth',
+ 'ms': 'markersize',
+ }
+
+
+def cycler(*args, **kwargs):
+ """
+ Create a `~cycler.Cycler` object much like :func:`cycler.cycler`,
+ but includes input validation.
+
+ Call signatures::
+
+ cycler(cycler)
+ cycler(label=values[, label2=values2[, ...]])
+ cycler(label, values)
+
+ Form 1 copies a given `~cycler.Cycler` object.
+
+ Form 2 creates a `~cycler.Cycler` which cycles over one or more
+ properties simultaneously. If multiple properties are given, their
+ value lists must have the same length.
+
+ Form 3 creates a `~cycler.Cycler` for a single property. This form
+ exists for compatibility with the original cycler. Its use is
+ discouraged in favor of the kwarg form, i.e. ``cycler(label=values)``.
+
+ Parameters
+ ----------
+ cycler : Cycler
+ Copy constructor for Cycler.
+
+ label : str
+ The property key. Must be a valid `.Artist` property.
+ For example, 'color' or 'linestyle'. Aliases are allowed,
+ such as 'c' for 'color' and 'lw' for 'linewidth'.
+
+ values : iterable
+ Finite-length iterable of the property values. These values
+ are validated and will raise a ValueError if invalid.
+
+ Returns
+ -------
+ Cycler
+ A new :class:`~cycler.Cycler` for the given properties.
+
+ Examples
+ --------
+ Creating a cycler for a single property:
+
+ >>> c = cycler(color=['red', 'green', 'blue'])
+
+ Creating a cycler for simultaneously cycling over multiple properties
+ (e.g. red circle, green plus, blue cross):
+
+ >>> c = cycler(color=['red', 'green', 'blue'],
+ ... marker=['o', '+', 'x'])
+
+ """
+ if args and kwargs:
+ raise TypeError("cycler() can only accept positional OR keyword "
+ "arguments -- not both.")
+ elif not args and not kwargs:
+ raise TypeError("cycler() must have positional OR keyword arguments")
+
+ if len(args) == 1:
+ if not isinstance(args[0], Cycler):
+ raise TypeError("If only one positional argument given, it must "
+ "be a Cycler instance.")
+ return validate_cycler(args[0])
+ elif len(args) == 2:
+ pairs = [(args[0], args[1])]
+ elif len(args) > 2:
+ raise TypeError("No more than 2 positional arguments allowed")
+ else:
+ pairs = kwargs.items()
+
+ validated = []
+ for prop, vals in pairs:
+ norm_prop = _prop_aliases.get(prop, prop)
+ validator = _prop_validators.get(norm_prop, None)
+ if validator is None:
+ raise TypeError("Unknown artist property: %s" % prop)
+ vals = validator(vals)
+ # We will normalize the property names as well to reduce
+ # the amount of alias handling code elsewhere.
+ validated.append((norm_prop, vals))
+
+ return reduce(operator.add, (ccycler(k, v) for k, v in validated))
+
+
+class _DunderChecker(ast.NodeVisitor):
+ def visit_Attribute(self, node):
+ if node.attr.startswith("__") and node.attr.endswith("__"):
+ raise ValueError("cycler strings with dunders are forbidden")
+ self.generic_visit(node)
+
+
+def validate_cycler(s):
+ """Return a Cycler object from a string repr or the object itself."""
+ if isinstance(s, str):
+ # TODO: We might want to rethink this...
+ # While I think I have it quite locked down, it is execution of
+ # arbitrary code without sanitation.
+ # Combine this with the possibility that rcparams might come from the
+ # internet (future plans), this could be downright dangerous.
+ # I locked it down by only having the 'cycler()' function available.
+ # UPDATE: Partly plugging a security hole.
+ # I really should have read this:
+ # https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
+ # We should replace this eval with a combo of PyParsing and
+ # ast.literal_eval()
+ try:
+ _DunderChecker().visit(ast.parse(s))
+ s = eval(s, {'cycler': cycler, '__builtins__': {}})
+ except BaseException as e:
+ raise ValueError(f"{s!r} is not a valid cycler construction: {e}"
+ ) from e
+ # Should make sure what comes from the above eval()
+ # is a Cycler object.
+ if isinstance(s, Cycler):
+ cycler_inst = s
+ else:
+ raise ValueError(f"Object is not a string or Cycler instance: {s!r}")
+
+ unknowns = cycler_inst.keys - (set(_prop_validators) | set(_prop_aliases))
+ if unknowns:
+ raise ValueError("Unknown artist properties: %s" % unknowns)
+
+ # Not a full validation, but it'll at least normalize property names
+ # A fuller validation would require v0.10 of cycler.
+ checker = set()
+ for prop in cycler_inst.keys:
+ norm_prop = _prop_aliases.get(prop, prop)
+ if norm_prop != prop and norm_prop in cycler_inst.keys:
+ raise ValueError(f"Cannot specify both {norm_prop!r} and alias "
+ f"{prop!r} in the same prop_cycle")
+ if norm_prop in checker:
+ raise ValueError(f"Another property was already aliased to "
+ f"{norm_prop!r}. Collision normalizing {prop!r}.")
+ checker.update([norm_prop])
+
+ # This is just an extra-careful check, just in case there is some
+ # edge-case I haven't thought of.
+ assert len(checker) == len(cycler_inst.keys)
+
+ # Now, it should be safe to mutate this cycler
+ for prop in cycler_inst.keys:
+ norm_prop = _prop_aliases.get(prop, prop)
+ cycler_inst.change_key(prop, norm_prop)
+
+ for key, vals in cycler_inst.by_key().items():
+ _prop_validators[key](vals)
+
+ return cycler_inst
+
+
+def validate_hist_bins(s):
+ valid_strs = ["auto", "sturges", "fd", "doane", "scott", "rice", "sqrt"]
+ if isinstance(s, str) and s in valid_strs:
+ return s
+ try:
+ return int(s)
+ except (TypeError, ValueError):
+ pass
+ try:
+ return validate_floatlist(s)
+ except ValueError:
+ pass
+ raise ValueError("'hist.bins' must be one of {}, an int or"
+ " a sequence of floats".format(valid_strs))
+
+
+class _ignorecase(list):
+ """A marker class indicating that a list-of-str is case-insensitive."""
+
+
+def _convert_validator_spec(key, conv):
+ if isinstance(conv, list):
+ ignorecase = isinstance(conv, _ignorecase)
+ return ValidateInStrings(key, conv, ignorecase=ignorecase)
+ else:
+ return conv
+
+
+# Mapping of rcParams to validators.
+# Converters given as lists or _ignorecase are converted to ValidateInStrings
+# immediately below.
+# The rcParams defaults are defined in lib/matplotlib/mpl-data/matplotlibrc, which
+# gets copied to matplotlib/mpl-data/matplotlibrc by the setup script.
+_validators = {
+ "backend": validate_backend,
+ "backend_fallback": validate_bool,
+ "figure.hooks": validate_stringlist,
+ "toolbar": _validate_toolbar,
+ "interactive": validate_bool,
+ "timezone": validate_string,
+
+ "webagg.port": validate_int,
+ "webagg.address": validate_string,
+ "webagg.open_in_browser": validate_bool,
+ "webagg.port_retries": validate_int,
+
+ # line props
+ "lines.linewidth": validate_float, # line width in points
+ "lines.linestyle": _validate_linestyle, # solid line
+ "lines.color": validate_color, # first color in color cycle
+ "lines.marker": validate_string, # marker name
+ "lines.markerfacecolor": validate_color_or_auto, # default color
+ "lines.markeredgecolor": validate_color_or_auto, # default color
+ "lines.markeredgewidth": validate_float,
+ "lines.markersize": validate_float, # markersize, in points
+ "lines.antialiased": validate_bool, # antialiased (no jaggies)
+ "lines.dash_joinstyle": JoinStyle,
+ "lines.solid_joinstyle": JoinStyle,
+ "lines.dash_capstyle": CapStyle,
+ "lines.solid_capstyle": CapStyle,
+ "lines.dashed_pattern": validate_floatlist,
+ "lines.dashdot_pattern": validate_floatlist,
+ "lines.dotted_pattern": validate_floatlist,
+ "lines.scale_dashes": validate_bool,
+
+ # marker props
+ "markers.fillstyle": validate_fillstyle,
+
+ ## pcolor(mesh) props:
+ "pcolor.shading": ["auto", "flat", "nearest", "gouraud"],
+ "pcolormesh.snap": validate_bool,
+
+ ## patch props
+ "patch.linewidth": validate_float, # line width in points
+ "patch.edgecolor": validate_color,
+ "patch.force_edgecolor": validate_bool,
+ "patch.facecolor": validate_color, # first color in cycle
+ "patch.antialiased": validate_bool, # antialiased (no jaggies)
+
+ ## hatch props
+ "hatch.color": validate_color,
+ "hatch.linewidth": validate_float,
+
+ ## Histogram properties
+ "hist.bins": validate_hist_bins,
+
+ ## Boxplot properties
+ "boxplot.notch": validate_bool,
+ "boxplot.vertical": validate_bool,
+ "boxplot.whiskers": validate_whiskers,
+ "boxplot.bootstrap": validate_int_or_None,
+ "boxplot.patchartist": validate_bool,
+ "boxplot.showmeans": validate_bool,
+ "boxplot.showcaps": validate_bool,
+ "boxplot.showbox": validate_bool,
+ "boxplot.showfliers": validate_bool,
+ "boxplot.meanline": validate_bool,
+
+ "boxplot.flierprops.color": validate_color,
+ "boxplot.flierprops.marker": validate_string,
+ "boxplot.flierprops.markerfacecolor": validate_color_or_auto,
+ "boxplot.flierprops.markeredgecolor": validate_color,
+ "boxplot.flierprops.markeredgewidth": validate_float,
+ "boxplot.flierprops.markersize": validate_float,
+ "boxplot.flierprops.linestyle": _validate_linestyle,
+ "boxplot.flierprops.linewidth": validate_float,
+
+ "boxplot.boxprops.color": validate_color,
+ "boxplot.boxprops.linewidth": validate_float,
+ "boxplot.boxprops.linestyle": _validate_linestyle,
+
+ "boxplot.whiskerprops.color": validate_color,
+ "boxplot.whiskerprops.linewidth": validate_float,
+ "boxplot.whiskerprops.linestyle": _validate_linestyle,
+
+ "boxplot.capprops.color": validate_color,
+ "boxplot.capprops.linewidth": validate_float,
+ "boxplot.capprops.linestyle": _validate_linestyle,
+
+ "boxplot.medianprops.color": validate_color,
+ "boxplot.medianprops.linewidth": validate_float,
+ "boxplot.medianprops.linestyle": _validate_linestyle,
+
+ "boxplot.meanprops.color": validate_color,
+ "boxplot.meanprops.marker": validate_string,
+ "boxplot.meanprops.markerfacecolor": validate_color,
+ "boxplot.meanprops.markeredgecolor": validate_color,
+ "boxplot.meanprops.markersize": validate_float,
+ "boxplot.meanprops.linestyle": _validate_linestyle,
+ "boxplot.meanprops.linewidth": validate_float,
+
+ ## font props
+ "font.family": validate_stringlist, # used by text object
+ "font.style": validate_string,
+ "font.variant": validate_string,
+ "font.stretch": validate_fontstretch,
+ "font.weight": validate_fontweight,
+ "font.size": validate_float, # Base font size in points
+ "font.serif": validate_stringlist,
+ "font.sans-serif": validate_stringlist,
+ "font.cursive": validate_stringlist,
+ "font.fantasy": validate_stringlist,
+ "font.monospace": validate_stringlist,
+
+ # text props
+ "text.color": validate_color,
+ "text.usetex": validate_bool,
+ "text.latex.preamble": validate_string,
+ "text.hinting": ["default", "no_autohint", "force_autohint",
+ "no_hinting", "auto", "native", "either", "none"],
+ "text.hinting_factor": validate_int,
+ "text.kerning_factor": validate_int,
+ "text.antialiased": validate_bool,
+ "text.parse_math": validate_bool,
+
+ "mathtext.cal": validate_font_properties,
+ "mathtext.rm": validate_font_properties,
+ "mathtext.tt": validate_font_properties,
+ "mathtext.it": validate_font_properties,
+ "mathtext.bf": validate_font_properties,
+ "mathtext.sf": validate_font_properties,
+ "mathtext.fontset": ["dejavusans", "dejavuserif", "cm", "stix",
+ "stixsans", "custom"],
+ "mathtext.default": ["rm", "cal", "it", "tt", "sf", "bf", "default",
+ "bb", "frak", "scr", "regular"],
+ "mathtext.fallback": _validate_mathtext_fallback,
+
+ "image.aspect": validate_aspect, # equal, auto, a number
+ "image.interpolation": validate_string,
+ "image.cmap": _validate_cmap, # gray, jet, etc.
+ "image.lut": validate_int, # lookup table
+ "image.origin": ["upper", "lower"],
+ "image.resample": validate_bool,
+ # Specify whether vector graphics backends will combine all images on a
+ # set of axes into a single composite image
+ "image.composite_image": validate_bool,
+
+ # contour props
+ "contour.negative_linestyle": _validate_linestyle,
+ "contour.corner_mask": validate_bool,
+ "contour.linewidth": validate_float_or_None,
+ "contour.algorithm": ["mpl2005", "mpl2014", "serial", "threaded"],
+
+ # errorbar props
+ "errorbar.capsize": validate_float,
+
+ # axis props
+ # alignment of x/y axis title
+ "xaxis.labellocation": ["left", "center", "right"],
+ "yaxis.labellocation": ["bottom", "center", "top"],
+
+ # axes props
+ "axes.axisbelow": validate_axisbelow,
+ "axes.facecolor": validate_color, # background color
+ "axes.edgecolor": validate_color, # edge color
+ "axes.linewidth": validate_float, # edge linewidth
+
+ "axes.spines.left": validate_bool, # Set visibility of axes spines,
+ "axes.spines.right": validate_bool, # i.e., the lines around the chart
+ "axes.spines.bottom": validate_bool, # denoting data boundary.
+ "axes.spines.top": validate_bool,
+
+ "axes.titlesize": validate_fontsize, # axes title fontsize
+ "axes.titlelocation": ["left", "center", "right"], # axes title alignment
+ "axes.titleweight": validate_fontweight, # axes title font weight
+ "axes.titlecolor": validate_color_or_auto, # axes title font color
+ # title location, axes units, None means auto
+ "axes.titley": validate_float_or_None,
+ # pad from axes top decoration to title in points
+ "axes.titlepad": validate_float,
+ "axes.grid": validate_bool, # display grid or not
+ "axes.grid.which": ["minor", "both", "major"], # which grids are drawn
+ "axes.grid.axis": ["x", "y", "both"], # grid type
+ "axes.labelsize": validate_fontsize, # fontsize of x & y labels
+ "axes.labelpad": validate_float, # space between label and axis
+ "axes.labelweight": validate_fontweight, # fontsize of x & y labels
+ "axes.labelcolor": validate_color, # color of axis label
+ # use scientific notation if log10 of the axis range is smaller than the
+ # first or larger than the second
+ "axes.formatter.limits": _listify_validator(validate_int, n=2),
+ # use current locale to format ticks
+ "axes.formatter.use_locale": validate_bool,
+ "axes.formatter.use_mathtext": validate_bool,
+ # minimum exponent to format in scientific notation
+ "axes.formatter.min_exponent": validate_int,
+ "axes.formatter.useoffset": validate_bool,
+ "axes.formatter.offset_threshold": validate_int,
+ "axes.unicode_minus": validate_bool,
+ # This entry can be either a cycler object or a string repr of a
+ # cycler-object, which gets eval()'ed to create the object.
+ "axes.prop_cycle": validate_cycler,
+ # If "data", axes limits are set close to the data.
+ # If "round_numbers" axes limits are set to the nearest round numbers.
+ "axes.autolimit_mode": ["data", "round_numbers"],
+ "axes.xmargin": _range_validators["0 <= x <= 1"], # margin added to xaxis
+ "axes.ymargin": _range_validators["0 <= x <= 1"], # margin added to yaxis
+ 'axes.zmargin': _range_validators["0 <= x <= 1"], # margin added to zaxis
+
+ "polaraxes.grid": validate_bool, # display polar grid or not
+ "axes3d.grid": validate_bool, # display 3d grid
+
+ "axes3d.xaxis.panecolor": validate_color, # 3d background pane
+ "axes3d.yaxis.panecolor": validate_color, # 3d background pane
+ "axes3d.zaxis.panecolor": validate_color, # 3d background pane
+
+ # scatter props
+ "scatter.marker": validate_string,
+ "scatter.edgecolors": validate_string,
+
+ "date.epoch": _validate_date,
+ "date.autoformatter.year": validate_string,
+ "date.autoformatter.month": validate_string,
+ "date.autoformatter.day": validate_string,
+ "date.autoformatter.hour": validate_string,
+ "date.autoformatter.minute": validate_string,
+ "date.autoformatter.second": validate_string,
+ "date.autoformatter.microsecond": validate_string,
+
+ 'date.converter': ['auto', 'concise'],
+ # for auto date locator, choose interval_multiples
+ 'date.interval_multiples': validate_bool,
+
+ # legend properties
+ "legend.fancybox": validate_bool,
+ "legend.loc": _ignorecase([
+ "best",
+ "upper right", "upper left", "lower left", "lower right", "right",
+ "center left", "center right", "lower center", "upper center",
+ "center"]),
+
+ # the number of points in the legend line
+ "legend.numpoints": validate_int,
+ # the number of points in the legend line for scatter
+ "legend.scatterpoints": validate_int,
+ "legend.fontsize": validate_fontsize,
+ "legend.title_fontsize": validate_fontsize_None,
+ # color of the legend
+ "legend.labelcolor": _validate_color_or_linecolor,
+ # the relative size of legend markers vs. original
+ "legend.markerscale": validate_float,
+ "legend.shadow": validate_bool,
+ # whether or not to draw a frame around legend
+ "legend.frameon": validate_bool,
+ # alpha value of the legend frame
+ "legend.framealpha": validate_float_or_None,
+
+ ## the following dimensions are in fraction of the font size
+ "legend.borderpad": validate_float, # units are fontsize
+ # the vertical space between the legend entries
+ "legend.labelspacing": validate_float,
+ # the length of the legend lines
+ "legend.handlelength": validate_float,
+ # the length of the legend lines
+ "legend.handleheight": validate_float,
+ # the space between the legend line and legend text
+ "legend.handletextpad": validate_float,
+ # the border between the axes and legend edge
+ "legend.borderaxespad": validate_float,
+ # the border between the axes and legend edge
+ "legend.columnspacing": validate_float,
+ "legend.facecolor": validate_color_or_inherit,
+ "legend.edgecolor": validate_color_or_inherit,
+
+ # tick properties
+ "xtick.top": validate_bool, # draw ticks on top side
+ "xtick.bottom": validate_bool, # draw ticks on bottom side
+ "xtick.labeltop": validate_bool, # draw label on top
+ "xtick.labelbottom": validate_bool, # draw label on bottom
+ "xtick.major.size": validate_float, # major xtick size in points
+ "xtick.minor.size": validate_float, # minor xtick size in points
+ "xtick.major.width": validate_float, # major xtick width in points
+ "xtick.minor.width": validate_float, # minor xtick width in points
+ "xtick.major.pad": validate_float, # distance to label in points
+ "xtick.minor.pad": validate_float, # distance to label in points
+ "xtick.color": validate_color, # color of xticks
+ "xtick.labelcolor": validate_color_or_inherit, # color of xtick labels
+ "xtick.minor.visible": validate_bool, # visibility of minor xticks
+ "xtick.minor.top": validate_bool, # draw top minor xticks
+ "xtick.minor.bottom": validate_bool, # draw bottom minor xticks
+ "xtick.major.top": validate_bool, # draw top major xticks
+ "xtick.major.bottom": validate_bool, # draw bottom major xticks
+ "xtick.labelsize": validate_fontsize, # fontsize of xtick labels
+ "xtick.direction": ["out", "in", "inout"], # direction of xticks
+ "xtick.alignment": ["center", "right", "left"],
+
+ "ytick.left": validate_bool, # draw ticks on left side
+ "ytick.right": validate_bool, # draw ticks on right side
+ "ytick.labelleft": validate_bool, # draw tick labels on left side
+ "ytick.labelright": validate_bool, # draw tick labels on right side
+ "ytick.major.size": validate_float, # major ytick size in points
+ "ytick.minor.size": validate_float, # minor ytick size in points
+ "ytick.major.width": validate_float, # major ytick width in points
+ "ytick.minor.width": validate_float, # minor ytick width in points
+ "ytick.major.pad": validate_float, # distance to label in points
+ "ytick.minor.pad": validate_float, # distance to label in points
+ "ytick.color": validate_color, # color of yticks
+ "ytick.labelcolor": validate_color_or_inherit, # color of ytick labels
+ "ytick.minor.visible": validate_bool, # visibility of minor yticks
+ "ytick.minor.left": validate_bool, # draw left minor yticks
+ "ytick.minor.right": validate_bool, # draw right minor yticks
+ "ytick.major.left": validate_bool, # draw left major yticks
+ "ytick.major.right": validate_bool, # draw right major yticks
+ "ytick.labelsize": validate_fontsize, # fontsize of ytick labels
+ "ytick.direction": ["out", "in", "inout"], # direction of yticks
+ "ytick.alignment": [
+ "center", "top", "bottom", "baseline", "center_baseline"],
+
+ "grid.color": validate_color, # grid color
+ "grid.linestyle": _validate_linestyle, # solid
+ "grid.linewidth": validate_float, # in points
+ "grid.alpha": validate_float,
+
+ ## figure props
+ # figure title
+ "figure.titlesize": validate_fontsize,
+ "figure.titleweight": validate_fontweight,
+
+ # figure labels
+ "figure.labelsize": validate_fontsize,
+ "figure.labelweight": validate_fontweight,
+
+ # figure size in inches: width by height
+ "figure.figsize": _listify_validator(validate_float, n=2),
+ "figure.dpi": validate_float,
+ "figure.facecolor": validate_color,
+ "figure.edgecolor": validate_color,
+ "figure.frameon": validate_bool,
+ "figure.autolayout": validate_bool,
+ "figure.max_open_warning": validate_int,
+ "figure.raise_window": validate_bool,
+
+ "figure.subplot.left": _range_validators["0 <= x <= 1"],
+ "figure.subplot.right": _range_validators["0 <= x <= 1"],
+ "figure.subplot.bottom": _range_validators["0 <= x <= 1"],
+ "figure.subplot.top": _range_validators["0 <= x <= 1"],
+ "figure.subplot.wspace": _range_validators["0 <= x < 1"],
+ "figure.subplot.hspace": _range_validators["0 <= x < 1"],
+
+ "figure.constrained_layout.use": validate_bool, # run constrained_layout?
+ # wspace and hspace are fraction of adjacent subplots to use for space.
+ # Much smaller than above because we don't need room for the text.
+ "figure.constrained_layout.hspace": _range_validators["0 <= x < 1"],
+ "figure.constrained_layout.wspace": _range_validators["0 <= x < 1"],
+ # buffer around the axes, in inches.
+ 'figure.constrained_layout.h_pad': validate_float,
+ 'figure.constrained_layout.w_pad': validate_float,
+
+ ## Saving figure's properties
+ 'savefig.dpi': validate_dpi,
+ 'savefig.facecolor': validate_color_or_auto,
+ 'savefig.edgecolor': validate_color_or_auto,
+ 'savefig.orientation': ['landscape', 'portrait'],
+ "savefig.format": validate_string,
+ "savefig.bbox": validate_bbox, # "tight", or "standard" (= None)
+ "savefig.pad_inches": validate_float,
+ # default directory in savefig dialog box
+ "savefig.directory": _validate_pathlike,
+ "savefig.transparent": validate_bool,
+
+ "tk.window_focus": validate_bool, # Maintain shell focus for TkAgg
+
+ # Set the papersize/type
+ "ps.papersize": _ignorecase(["auto", "letter", "legal", "ledger",
+ *[f"{ab}{i}"
+ for ab in "ab" for i in range(11)]]),
+ "ps.useafm": validate_bool,
+ # use ghostscript or xpdf to distill ps output
+ "ps.usedistiller": validate_ps_distiller,
+ "ps.distiller.res": validate_int, # dpi
+ "ps.fonttype": validate_fonttype, # 3 (Type3) or 42 (Truetype)
+ "pdf.compression": validate_int, # 0-9 compression level; 0 to disable
+ "pdf.inheritcolor": validate_bool, # skip color setting commands
+ # use only the 14 PDF core fonts embedded in every PDF viewing application
+ "pdf.use14corefonts": validate_bool,
+ "pdf.fonttype": validate_fonttype, # 3 (Type3) or 42 (Truetype)
+
+ "pgf.texsystem": ["xelatex", "lualatex", "pdflatex"], # latex variant used
+ "pgf.rcfonts": validate_bool, # use mpl's rc settings for font config
+ "pgf.preamble": validate_string, # custom LaTeX preamble
+
+ # write raster image data into the svg file
+ "svg.image_inline": validate_bool,
+ "svg.fonttype": ["none", "path"], # save text as text ("none") or "paths"
+ "svg.hashsalt": validate_string_or_None,
+
+ # set this when you want to generate hardcopy docstring
+ "docstring.hardcopy": validate_bool,
+
+ "path.simplify": validate_bool,
+ "path.simplify_threshold": _range_validators["0 <= x <= 1"],
+ "path.snap": validate_bool,
+ "path.sketch": validate_sketch,
+ "path.effects": validate_anylist,
+ "agg.path.chunksize": validate_int, # 0 to disable chunking
+
+ # key-mappings (multi-character mappings should be a list/tuple)
+ "keymap.fullscreen": validate_stringlist,
+ "keymap.home": validate_stringlist,
+ "keymap.back": validate_stringlist,
+ "keymap.forward": validate_stringlist,
+ "keymap.pan": validate_stringlist,
+ "keymap.zoom": validate_stringlist,
+ "keymap.save": validate_stringlist,
+ "keymap.quit": validate_stringlist,
+ "keymap.quit_all": validate_stringlist, # e.g.: "W", "cmd+W", "Q"
+ "keymap.grid": validate_stringlist,
+ "keymap.grid_minor": validate_stringlist,
+ "keymap.yscale": validate_stringlist,
+ "keymap.xscale": validate_stringlist,
+ "keymap.help": validate_stringlist,
+ "keymap.copy": validate_stringlist,
+
+ # Animation settings
+ "animation.html": ["html5", "jshtml", "none"],
+ # Limit, in MB, of size of base64 encoded animation in HTML
+ # (i.e. IPython notebook)
+ "animation.embed_limit": validate_float,
+ "animation.writer": validate_string,
+ "animation.codec": validate_string,
+ "animation.bitrate": validate_int,
+ # Controls image format when frames are written to disk
+ "animation.frame_format": ["png", "jpeg", "tiff", "raw", "rgba", "ppm",
+ "sgi", "bmp", "pbm", "svg"],
+ # Path to ffmpeg binary. If just binary name, subprocess uses $PATH.
+ "animation.ffmpeg_path": _validate_pathlike,
+ # Additional arguments for ffmpeg movie writer (using pipes)
+ "animation.ffmpeg_args": validate_stringlist,
+ # Path to convert binary. If just binary name, subprocess uses $PATH.
+ "animation.convert_path": _validate_pathlike,
+ # Additional arguments for convert movie writer (using pipes)
+ "animation.convert_args": validate_stringlist,
+
+ # Classic (pre 2.0) compatibility mode
+ # This is used for things that are hard to make backward compatible
+ # with a sane rcParam alone. This does *not* turn on classic mode
+ # altogether. For that use `matplotlib.style.use("classic")`.
+ "_internal.classic_mode": validate_bool
+}
+_hardcoded_defaults = { # Defaults not inferred from
+ # lib/matplotlib/mpl-data/matplotlibrc...
+ # ... because they are private:
+ "_internal.classic_mode": False,
+ # ... because they are deprecated:
+ # No current deprecations.
+ # backend is handled separately when constructing rcParamsDefault.
+}
+_validators = {k: _convert_validator_spec(k, conv)
+ for k, conv in _validators.items()}
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/sankey.py b/omnilmm/lib/python3.10/site-packages/matplotlib/sankey.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ebae572e7e5e7050ae852c17d4c4604378f5887
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/sankey.py
@@ -0,0 +1,822 @@
+"""
+Module for creating Sankey diagrams using Matplotlib.
+"""
+
+import logging
+from types import SimpleNamespace
+
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib.path import Path
+from matplotlib.patches import PathPatch
+from matplotlib.transforms import Affine2D
+from matplotlib import _docstring
+
+_log = logging.getLogger(__name__)
+
+__author__ = "Kevin L. Davies"
+__credits__ = ["Yannick Copin"]
+__license__ = "BSD"
+__version__ = "2011/09/16"
+
+# Angles [deg/90]
+RIGHT = 0
+UP = 1
+# LEFT = 2
+DOWN = 3
+
+
+class Sankey:
+ """
+ Sankey diagram.
+
+ Sankey diagrams are a specific type of flow diagram, in which
+ the width of the arrows is shown proportionally to the flow
+ quantity. They are typically used to visualize energy or
+ material or cost transfers between processes.
+ `Wikipedia (6/1/2011) `_
+
+ """
+
+ def __init__(self, ax=None, scale=1.0, unit='', format='%G', gap=0.25,
+ radius=0.1, shoulder=0.03, offset=0.15, head_angle=100,
+ margin=0.4, tolerance=1e-6, **kwargs):
+ """
+ Create a new Sankey instance.
+
+ The optional arguments listed below are applied to all subdiagrams so
+ that there is consistent alignment and formatting.
+
+ In order to draw a complex Sankey diagram, create an instance of
+ :class:`Sankey` by calling it without any kwargs::
+
+ sankey = Sankey()
+
+ Then add simple Sankey sub-diagrams::
+
+ sankey.add() # 1
+ sankey.add() # 2
+ #...
+ sankey.add() # n
+
+ Finally, create the full diagram::
+
+ sankey.finish()
+
+ Or, instead, simply daisy-chain those calls::
+
+ Sankey().add().add... .add().finish()
+
+ Other Parameters
+ ----------------
+ ax : `~matplotlib.axes.Axes`
+ Axes onto which the data should be plotted. If *ax* isn't
+ provided, new Axes will be created.
+ scale : float
+ Scaling factor for the flows. *scale* sizes the width of the paths
+ in order to maintain proper layout. The same scale is applied to
+ all subdiagrams. The value should be chosen such that the product
+ of the scale and the sum of the inputs is approximately 1.0 (and
+ the product of the scale and the sum of the outputs is
+ approximately -1.0).
+ unit : str
+ The physical unit associated with the flow quantities. If *unit*
+ is None, then none of the quantities are labeled.
+ format : str or callable
+ A Python number formatting string or callable used to label the
+ flows with their quantities (i.e., a number times a unit, where the
+ unit is given). If a format string is given, the label will be
+ ``format % quantity``. If a callable is given, it will be called
+ with ``quantity`` as an argument.
+ gap : float
+ Space between paths that break in/break away to/from the top or
+ bottom.
+ radius : float
+ Inner radius of the vertical paths.
+ shoulder : float
+ Size of the shoulders of output arrows.
+ offset : float
+ Text offset (from the dip or tip of the arrow).
+ head_angle : float
+ Angle, in degrees, of the arrow heads (and negative of the angle of
+ the tails).
+ margin : float
+ Minimum space between Sankey outlines and the edge of the plot
+ area.
+ tolerance : float
+ Acceptable maximum of the magnitude of the sum of flows. The
+ magnitude of the sum of connected flows cannot be greater than
+ *tolerance*.
+ **kwargs
+ Any additional keyword arguments will be passed to :meth:`add`,
+ which will create the first subdiagram.
+
+ See Also
+ --------
+ Sankey.add
+ Sankey.finish
+
+ Examples
+ --------
+ .. plot:: gallery/specialty_plots/sankey_basics.py
+ """
+ # Check the arguments.
+ if gap < 0:
+ raise ValueError(
+ "'gap' is negative, which is not allowed because it would "
+ "cause the paths to overlap")
+ if radius > gap:
+ raise ValueError(
+ "'radius' is greater than 'gap', which is not allowed because "
+ "it would cause the paths to overlap")
+ if head_angle < 0:
+ raise ValueError(
+ "'head_angle' is negative, which is not allowed because it "
+ "would cause inputs to look like outputs and vice versa")
+ if tolerance < 0:
+ raise ValueError(
+ "'tolerance' is negative, but it must be a magnitude")
+
+ # Create axes if necessary.
+ if ax is None:
+ import matplotlib.pyplot as plt
+ fig = plt.figure()
+ ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[])
+
+ self.diagrams = []
+
+ # Store the inputs.
+ self.ax = ax
+ self.unit = unit
+ self.format = format
+ self.scale = scale
+ self.gap = gap
+ self.radius = radius
+ self.shoulder = shoulder
+ self.offset = offset
+ self.margin = margin
+ self.pitch = np.tan(np.pi * (1 - head_angle / 180.0) / 2.0)
+ self.tolerance = tolerance
+
+ # Initialize the vertices of tight box around the diagram(s).
+ self.extent = np.array((np.inf, -np.inf, np.inf, -np.inf))
+
+ # If there are any kwargs, create the first subdiagram.
+ if len(kwargs):
+ self.add(**kwargs)
+
+ def _arc(self, quadrant=0, cw=True, radius=1, center=(0, 0)):
+ """
+ Return the codes and vertices for a rotated, scaled, and translated
+ 90 degree arc.
+
+ Other Parameters
+ ----------------
+ quadrant : {0, 1, 2, 3}, default: 0
+ Uses 0-based indexing (0, 1, 2, or 3).
+ cw : bool, default: True
+ If True, the arc vertices are produced clockwise; counter-clockwise
+ otherwise.
+ radius : float, default: 1
+ The radius of the arc.
+ center : (float, float), default: (0, 0)
+ (x, y) tuple of the arc's center.
+ """
+ # Note: It would be possible to use matplotlib's transforms to rotate,
+ # scale, and translate the arc, but since the angles are discrete,
+ # it's just as easy and maybe more efficient to do it here.
+ ARC_CODES = [Path.LINETO,
+ Path.CURVE4,
+ Path.CURVE4,
+ Path.CURVE4,
+ Path.CURVE4,
+ Path.CURVE4,
+ Path.CURVE4]
+ # Vertices of a cubic Bezier curve approximating a 90 deg arc
+ # These can be determined by Path.arc(0, 90).
+ ARC_VERTICES = np.array([[1.00000000e+00, 0.00000000e+00],
+ [1.00000000e+00, 2.65114773e-01],
+ [8.94571235e-01, 5.19642327e-01],
+ [7.07106781e-01, 7.07106781e-01],
+ [5.19642327e-01, 8.94571235e-01],
+ [2.65114773e-01, 1.00000000e+00],
+ # Insignificant
+ # [6.12303177e-17, 1.00000000e+00]])
+ [0.00000000e+00, 1.00000000e+00]])
+ if quadrant in (0, 2):
+ if cw:
+ vertices = ARC_VERTICES
+ else:
+ vertices = ARC_VERTICES[:, ::-1] # Swap x and y.
+ else: # 1, 3
+ # Negate x.
+ if cw:
+ # Swap x and y.
+ vertices = np.column_stack((-ARC_VERTICES[:, 1],
+ ARC_VERTICES[:, 0]))
+ else:
+ vertices = np.column_stack((-ARC_VERTICES[:, 0],
+ ARC_VERTICES[:, 1]))
+ if quadrant > 1:
+ radius = -radius # Rotate 180 deg.
+ return list(zip(ARC_CODES, radius * vertices +
+ np.tile(center, (ARC_VERTICES.shape[0], 1))))
+
+ def _add_input(self, path, angle, flow, length):
+ """
+ Add an input to a path and return its tip and label locations.
+ """
+ if angle is None:
+ return [0, 0], [0, 0]
+ else:
+ x, y = path[-1][1] # Use the last point as a reference.
+ dipdepth = (flow / 2) * self.pitch
+ if angle == RIGHT:
+ x -= length
+ dip = [x + dipdepth, y + flow / 2.0]
+ path.extend([(Path.LINETO, [x, y]),
+ (Path.LINETO, dip),
+ (Path.LINETO, [x, y + flow]),
+ (Path.LINETO, [x + self.gap, y + flow])])
+ label_location = [dip[0] - self.offset, dip[1]]
+ else: # Vertical
+ x -= self.gap
+ if angle == UP:
+ sign = 1
+ else:
+ sign = -1
+
+ dip = [x - flow / 2, y - sign * (length - dipdepth)]
+ if angle == DOWN:
+ quadrant = 2
+ else:
+ quadrant = 1
+
+ # Inner arc isn't needed if inner radius is zero
+ if self.radius:
+ path.extend(self._arc(quadrant=quadrant,
+ cw=angle == UP,
+ radius=self.radius,
+ center=(x + self.radius,
+ y - sign * self.radius)))
+ else:
+ path.append((Path.LINETO, [x, y]))
+ path.extend([(Path.LINETO, [x, y - sign * length]),
+ (Path.LINETO, dip),
+ (Path.LINETO, [x - flow, y - sign * length])])
+ path.extend(self._arc(quadrant=quadrant,
+ cw=angle == DOWN,
+ radius=flow + self.radius,
+ center=(x + self.radius,
+ y - sign * self.radius)))
+ path.append((Path.LINETO, [x - flow, y + sign * flow]))
+ label_location = [dip[0], dip[1] - sign * self.offset]
+
+ return dip, label_location
+
+ def _add_output(self, path, angle, flow, length):
+ """
+ Append an output to a path and return its tip and label locations.
+
+ .. note:: *flow* is negative for an output.
+ """
+ if angle is None:
+ return [0, 0], [0, 0]
+ else:
+ x, y = path[-1][1] # Use the last point as a reference.
+ tipheight = (self.shoulder - flow / 2) * self.pitch
+ if angle == RIGHT:
+ x += length
+ tip = [x + tipheight, y + flow / 2.0]
+ path.extend([(Path.LINETO, [x, y]),
+ (Path.LINETO, [x, y + self.shoulder]),
+ (Path.LINETO, tip),
+ (Path.LINETO, [x, y - self.shoulder + flow]),
+ (Path.LINETO, [x, y + flow]),
+ (Path.LINETO, [x - self.gap, y + flow])])
+ label_location = [tip[0] + self.offset, tip[1]]
+ else: # Vertical
+ x += self.gap
+ if angle == UP:
+ sign, quadrant = 1, 3
+ else:
+ sign, quadrant = -1, 0
+
+ tip = [x - flow / 2.0, y + sign * (length + tipheight)]
+ # Inner arc isn't needed if inner radius is zero
+ if self.radius:
+ path.extend(self._arc(quadrant=quadrant,
+ cw=angle == UP,
+ radius=self.radius,
+ center=(x - self.radius,
+ y + sign * self.radius)))
+ else:
+ path.append((Path.LINETO, [x, y]))
+ path.extend([(Path.LINETO, [x, y + sign * length]),
+ (Path.LINETO, [x - self.shoulder,
+ y + sign * length]),
+ (Path.LINETO, tip),
+ (Path.LINETO, [x + self.shoulder - flow,
+ y + sign * length]),
+ (Path.LINETO, [x - flow, y + sign * length])])
+ path.extend(self._arc(quadrant=quadrant,
+ cw=angle == DOWN,
+ radius=self.radius - flow,
+ center=(x - self.radius,
+ y + sign * self.radius)))
+ path.append((Path.LINETO, [x - flow, y + sign * flow]))
+ label_location = [tip[0], tip[1] + sign * self.offset]
+ return tip, label_location
+
+ def _revert(self, path, first_action=Path.LINETO):
+ """
+ A path is not simply reversible by path[::-1] since the code
+ specifies an action to take from the **previous** point.
+ """
+ reverse_path = []
+ next_code = first_action
+ for code, position in path[::-1]:
+ reverse_path.append((next_code, position))
+ next_code = code
+ return reverse_path
+ # This might be more efficient, but it fails because 'tuple' object
+ # doesn't support item assignment:
+ # path[1] = path[1][-1:0:-1]
+ # path[1][0] = first_action
+ # path[2] = path[2][::-1]
+ # return path
+
+ @_docstring.dedent_interpd
+ def add(self, patchlabel='', flows=None, orientations=None, labels='',
+ trunklength=1.0, pathlengths=0.25, prior=None, connect=(0, 0),
+ rotation=0, **kwargs):
+ """
+ Add a simple Sankey diagram with flows at the same hierarchical level.
+
+ Parameters
+ ----------
+ patchlabel : str
+ Label to be placed at the center of the diagram.
+ Note that *label* (not *patchlabel*) can be passed as keyword
+ argument to create an entry in the legend.
+
+ flows : list of float
+ Array of flow values. By convention, inputs are positive and
+ outputs are negative.
+
+ Flows are placed along the top of the diagram from the inside out
+ in order of their index within *flows*. They are placed along the
+ sides of the diagram from the top down and along the bottom from
+ the outside in.
+
+ If the sum of the inputs and outputs is
+ nonzero, the discrepancy will appear as a cubic Bézier curve along
+ the top and bottom edges of the trunk.
+
+ orientations : list of {-1, 0, 1}
+ List of orientations of the flows (or a single orientation to be
+ used for all flows). Valid values are 0 (inputs from
+ the left, outputs to the right), 1 (from and to the top) or -1
+ (from and to the bottom).
+
+ labels : list of (str or None)
+ List of labels for the flows (or a single label to be used for all
+ flows). Each label may be *None* (no label), or a labeling string.
+ If an entry is a (possibly empty) string, then the quantity for the
+ corresponding flow will be shown below the string. However, if
+ the *unit* of the main diagram is None, then quantities are never
+ shown, regardless of the value of this argument.
+
+ trunklength : float
+ Length between the bases of the input and output groups (in
+ data-space units).
+
+ pathlengths : list of float
+ List of lengths of the vertical arrows before break-in or after
+ break-away. If a single value is given, then it will be applied to
+ the first (inside) paths on the top and bottom, and the length of
+ all other arrows will be justified accordingly. The *pathlengths*
+ are not applied to the horizontal inputs and outputs.
+
+ prior : int
+ Index of the prior diagram to which this diagram should be
+ connected.
+
+ connect : (int, int)
+ A (prior, this) tuple indexing the flow of the prior diagram and
+ the flow of this diagram which should be connected. If this is the
+ first diagram or *prior* is *None*, *connect* will be ignored.
+
+ rotation : float
+ Angle of rotation of the diagram in degrees. The interpretation of
+ the *orientations* argument will be rotated accordingly (e.g., if
+ *rotation* == 90, an *orientations* entry of 1 means to/from the
+ left). *rotation* is ignored if this diagram is connected to an
+ existing one (using *prior* and *connect*).
+
+ Returns
+ -------
+ Sankey
+ The current `.Sankey` instance.
+
+ Other Parameters
+ ----------------
+ **kwargs
+ Additional keyword arguments set `matplotlib.patches.PathPatch`
+ properties, listed below. For example, one may want to use
+ ``fill=False`` or ``label="A legend entry"``.
+
+ %(Patch:kwdoc)s
+
+ See Also
+ --------
+ Sankey.finish
+ """
+ # Check and preprocess the arguments.
+ flows = np.array([1.0, -1.0]) if flows is None else np.array(flows)
+ n = flows.shape[0] # Number of flows
+ if rotation is None:
+ rotation = 0
+ else:
+ # In the code below, angles are expressed in deg/90.
+ rotation /= 90.0
+ if orientations is None:
+ orientations = 0
+ try:
+ orientations = np.broadcast_to(orientations, n)
+ except ValueError:
+ raise ValueError(
+ f"The shapes of 'flows' {np.shape(flows)} and 'orientations' "
+ f"{np.shape(orientations)} are incompatible"
+ ) from None
+ try:
+ labels = np.broadcast_to(labels, n)
+ except ValueError:
+ raise ValueError(
+ f"The shapes of 'flows' {np.shape(flows)} and 'labels' "
+ f"{np.shape(labels)} are incompatible"
+ ) from None
+ if trunklength < 0:
+ raise ValueError(
+ "'trunklength' is negative, which is not allowed because it "
+ "would cause poor layout")
+ if abs(np.sum(flows)) > self.tolerance:
+ _log.info("The sum of the flows is nonzero (%f; patchlabel=%r); "
+ "is the system not at steady state?",
+ np.sum(flows), patchlabel)
+ scaled_flows = self.scale * flows
+ gain = sum(max(flow, 0) for flow in scaled_flows)
+ loss = sum(min(flow, 0) for flow in scaled_flows)
+ if prior is not None:
+ if prior < 0:
+ raise ValueError("The index of the prior diagram is negative")
+ if min(connect) < 0:
+ raise ValueError(
+ "At least one of the connection indices is negative")
+ if prior >= len(self.diagrams):
+ raise ValueError(
+ f"The index of the prior diagram is {prior}, but there "
+ f"are only {len(self.diagrams)} other diagrams")
+ if connect[0] >= len(self.diagrams[prior].flows):
+ raise ValueError(
+ "The connection index to the source diagram is {}, but "
+ "that diagram has only {} flows".format(
+ connect[0], len(self.diagrams[prior].flows)))
+ if connect[1] >= n:
+ raise ValueError(
+ f"The connection index to this diagram is {connect[1]}, "
+ f"but this diagram has only {n} flows")
+ if self.diagrams[prior].angles[connect[0]] is None:
+ raise ValueError(
+ f"The connection cannot be made, which may occur if the "
+ f"magnitude of flow {connect[0]} of diagram {prior} is "
+ f"less than the specified tolerance")
+ flow_error = (self.diagrams[prior].flows[connect[0]] +
+ flows[connect[1]])
+ if abs(flow_error) >= self.tolerance:
+ raise ValueError(
+ f"The scaled sum of the connected flows is {flow_error}, "
+ f"which is not within the tolerance ({self.tolerance})")
+
+ # Determine if the flows are inputs.
+ are_inputs = [None] * n
+ for i, flow in enumerate(flows):
+ if flow >= self.tolerance:
+ are_inputs[i] = True
+ elif flow <= -self.tolerance:
+ are_inputs[i] = False
+ else:
+ _log.info(
+ "The magnitude of flow %d (%f) is below the tolerance "
+ "(%f).\nIt will not be shown, and it cannot be used in a "
+ "connection.", i, flow, self.tolerance)
+
+ # Determine the angles of the arrows (before rotation).
+ angles = [None] * n
+ for i, (orient, is_input) in enumerate(zip(orientations, are_inputs)):
+ if orient == 1:
+ if is_input:
+ angles[i] = DOWN
+ elif is_input is False:
+ # Be specific since is_input can be None.
+ angles[i] = UP
+ elif orient == 0:
+ if is_input is not None:
+ angles[i] = RIGHT
+ else:
+ if orient != -1:
+ raise ValueError(
+ f"The value of orientations[{i}] is {orient}, "
+ f"but it must be -1, 0, or 1")
+ if is_input:
+ angles[i] = UP
+ elif is_input is False:
+ angles[i] = DOWN
+
+ # Justify the lengths of the paths.
+ if np.iterable(pathlengths):
+ if len(pathlengths) != n:
+ raise ValueError(
+ f"The lengths of 'flows' ({n}) and 'pathlengths' "
+ f"({len(pathlengths)}) are incompatible")
+ else: # Make pathlengths into a list.
+ urlength = pathlengths
+ ullength = pathlengths
+ lrlength = pathlengths
+ lllength = pathlengths
+ d = dict(RIGHT=pathlengths)
+ pathlengths = [d.get(angle, 0) for angle in angles]
+ # Determine the lengths of the top-side arrows
+ # from the middle outwards.
+ for i, (angle, is_input, flow) in enumerate(zip(angles, are_inputs,
+ scaled_flows)):
+ if angle == DOWN and is_input:
+ pathlengths[i] = ullength
+ ullength += flow
+ elif angle == UP and is_input is False:
+ pathlengths[i] = urlength
+ urlength -= flow # Flow is negative for outputs.
+ # Determine the lengths of the bottom-side arrows
+ # from the middle outwards.
+ for i, (angle, is_input, flow) in enumerate(reversed(list(zip(
+ angles, are_inputs, scaled_flows)))):
+ if angle == UP and is_input:
+ pathlengths[n - i - 1] = lllength
+ lllength += flow
+ elif angle == DOWN and is_input is False:
+ pathlengths[n - i - 1] = lrlength
+ lrlength -= flow
+ # Determine the lengths of the left-side arrows
+ # from the bottom upwards.
+ has_left_input = False
+ for i, (angle, is_input, spec) in enumerate(reversed(list(zip(
+ angles, are_inputs, zip(scaled_flows, pathlengths))))):
+ if angle == RIGHT:
+ if is_input:
+ if has_left_input:
+ pathlengths[n - i - 1] = 0
+ else:
+ has_left_input = True
+ # Determine the lengths of the right-side arrows
+ # from the top downwards.
+ has_right_output = False
+ for i, (angle, is_input, spec) in enumerate(zip(
+ angles, are_inputs, list(zip(scaled_flows, pathlengths)))):
+ if angle == RIGHT:
+ if is_input is False:
+ if has_right_output:
+ pathlengths[i] = 0
+ else:
+ has_right_output = True
+
+ # Begin the subpaths, and smooth the transition if the sum of the flows
+ # is nonzero.
+ urpath = [(Path.MOVETO, [(self.gap - trunklength / 2.0), # Upper right
+ gain / 2.0]),
+ (Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0,
+ gain / 2.0]),
+ (Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0,
+ gain / 2.0]),
+ (Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0,
+ -loss / 2.0]),
+ (Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0,
+ -loss / 2.0]),
+ (Path.LINETO, [(trunklength / 2.0 - self.gap),
+ -loss / 2.0])]
+ llpath = [(Path.LINETO, [(trunklength / 2.0 - self.gap), # Lower left
+ loss / 2.0]),
+ (Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0,
+ loss / 2.0]),
+ (Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0,
+ loss / 2.0]),
+ (Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0,
+ -gain / 2.0]),
+ (Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0,
+ -gain / 2.0]),
+ (Path.LINETO, [(self.gap - trunklength / 2.0),
+ -gain / 2.0])]
+ lrpath = [(Path.LINETO, [(trunklength / 2.0 - self.gap), # Lower right
+ loss / 2.0])]
+ ulpath = [(Path.LINETO, [self.gap - trunklength / 2.0, # Upper left
+ gain / 2.0])]
+
+ # Add the subpaths and assign the locations of the tips and labels.
+ tips = np.zeros((n, 2))
+ label_locations = np.zeros((n, 2))
+ # Add the top-side inputs and outputs from the middle outwards.
+ for i, (angle, is_input, spec) in enumerate(zip(
+ angles, are_inputs, list(zip(scaled_flows, pathlengths)))):
+ if angle == DOWN and is_input:
+ tips[i, :], label_locations[i, :] = self._add_input(
+ ulpath, angle, *spec)
+ elif angle == UP and is_input is False:
+ tips[i, :], label_locations[i, :] = self._add_output(
+ urpath, angle, *spec)
+ # Add the bottom-side inputs and outputs from the middle outwards.
+ for i, (angle, is_input, spec) in enumerate(reversed(list(zip(
+ angles, are_inputs, list(zip(scaled_flows, pathlengths)))))):
+ if angle == UP and is_input:
+ tip, label_location = self._add_input(llpath, angle, *spec)
+ tips[n - i - 1, :] = tip
+ label_locations[n - i - 1, :] = label_location
+ elif angle == DOWN and is_input is False:
+ tip, label_location = self._add_output(lrpath, angle, *spec)
+ tips[n - i - 1, :] = tip
+ label_locations[n - i - 1, :] = label_location
+ # Add the left-side inputs from the bottom upwards.
+ has_left_input = False
+ for i, (angle, is_input, spec) in enumerate(reversed(list(zip(
+ angles, are_inputs, list(zip(scaled_flows, pathlengths)))))):
+ if angle == RIGHT and is_input:
+ if not has_left_input:
+ # Make sure the lower path extends
+ # at least as far as the upper one.
+ if llpath[-1][1][0] > ulpath[-1][1][0]:
+ llpath.append((Path.LINETO, [ulpath[-1][1][0],
+ llpath[-1][1][1]]))
+ has_left_input = True
+ tip, label_location = self._add_input(llpath, angle, *spec)
+ tips[n - i - 1, :] = tip
+ label_locations[n - i - 1, :] = label_location
+ # Add the right-side outputs from the top downwards.
+ has_right_output = False
+ for i, (angle, is_input, spec) in enumerate(zip(
+ angles, are_inputs, list(zip(scaled_flows, pathlengths)))):
+ if angle == RIGHT and is_input is False:
+ if not has_right_output:
+ # Make sure the upper path extends
+ # at least as far as the lower one.
+ if urpath[-1][1][0] < lrpath[-1][1][0]:
+ urpath.append((Path.LINETO, [lrpath[-1][1][0],
+ urpath[-1][1][1]]))
+ has_right_output = True
+ tips[i, :], label_locations[i, :] = self._add_output(
+ urpath, angle, *spec)
+ # Trim any hanging vertices.
+ if not has_left_input:
+ ulpath.pop()
+ llpath.pop()
+ if not has_right_output:
+ lrpath.pop()
+ urpath.pop()
+
+ # Concatenate the subpaths in the correct order (clockwise from top).
+ path = (urpath + self._revert(lrpath) + llpath + self._revert(ulpath) +
+ [(Path.CLOSEPOLY, urpath[0][1])])
+
+ # Create a patch with the Sankey outline.
+ codes, vertices = zip(*path)
+ vertices = np.array(vertices)
+
+ def _get_angle(a, r):
+ if a is None:
+ return None
+ else:
+ return a + r
+
+ if prior is None:
+ if rotation != 0: # By default, none of this is needed.
+ angles = [_get_angle(angle, rotation) for angle in angles]
+ rotate = Affine2D().rotate_deg(rotation * 90).transform_affine
+ tips = rotate(tips)
+ label_locations = rotate(label_locations)
+ vertices = rotate(vertices)
+ text = self.ax.text(0, 0, s=patchlabel, ha='center', va='center')
+ else:
+ rotation = (self.diagrams[prior].angles[connect[0]] -
+ angles[connect[1]])
+ angles = [_get_angle(angle, rotation) for angle in angles]
+ rotate = Affine2D().rotate_deg(rotation * 90).transform_affine
+ tips = rotate(tips)
+ offset = self.diagrams[prior].tips[connect[0]] - tips[connect[1]]
+ translate = Affine2D().translate(*offset).transform_affine
+ tips = translate(tips)
+ label_locations = translate(rotate(label_locations))
+ vertices = translate(rotate(vertices))
+ kwds = dict(s=patchlabel, ha='center', va='center')
+ text = self.ax.text(*offset, **kwds)
+ if mpl.rcParams['_internal.classic_mode']:
+ fc = kwargs.pop('fc', kwargs.pop('facecolor', '#bfd1d4'))
+ lw = kwargs.pop('lw', kwargs.pop('linewidth', 0.5))
+ else:
+ fc = kwargs.pop('fc', kwargs.pop('facecolor', None))
+ lw = kwargs.pop('lw', kwargs.pop('linewidth', None))
+ if fc is None:
+ fc = next(self.ax._get_patches_for_fill.prop_cycler)['color']
+ patch = PathPatch(Path(vertices, codes), fc=fc, lw=lw, **kwargs)
+ self.ax.add_patch(patch)
+
+ # Add the path labels.
+ texts = []
+ for number, angle, label, location in zip(flows, angles, labels,
+ label_locations):
+ if label is None or angle is None:
+ label = ''
+ elif self.unit is not None:
+ if isinstance(self.format, str):
+ quantity = self.format % abs(number) + self.unit
+ elif callable(self.format):
+ quantity = self.format(number)
+ else:
+ raise TypeError(
+ 'format must be callable or a format string')
+ if label != '':
+ label += "\n"
+ label += quantity
+ texts.append(self.ax.text(x=location[0], y=location[1],
+ s=label,
+ ha='center', va='center'))
+ # Text objects are placed even they are empty (as long as the magnitude
+ # of the corresponding flow is larger than the tolerance) in case the
+ # user wants to provide labels later.
+
+ # Expand the size of the diagram if necessary.
+ self.extent = (min(np.min(vertices[:, 0]),
+ np.min(label_locations[:, 0]),
+ self.extent[0]),
+ max(np.max(vertices[:, 0]),
+ np.max(label_locations[:, 0]),
+ self.extent[1]),
+ min(np.min(vertices[:, 1]),
+ np.min(label_locations[:, 1]),
+ self.extent[2]),
+ max(np.max(vertices[:, 1]),
+ np.max(label_locations[:, 1]),
+ self.extent[3]))
+ # Include both vertices _and_ label locations in the extents; there are
+ # where either could determine the margins (e.g., arrow shoulders).
+
+ # Add this diagram as a subdiagram.
+ self.diagrams.append(
+ SimpleNamespace(patch=patch, flows=flows, angles=angles, tips=tips,
+ text=text, texts=texts))
+
+ # Allow a daisy-chained call structure (see docstring for the class).
+ return self
+
+ def finish(self):
+ """
+ Adjust the axes and return a list of information about the Sankey
+ subdiagram(s).
+
+ Return value is a list of subdiagrams represented with the following
+ fields:
+
+ =============== ===================================================
+ Field Description
+ =============== ===================================================
+ *patch* Sankey outline (an instance of
+ :class:`~matplotlib.patches.PathPatch`)
+ *flows* values of the flows (positive for input, negative
+ for output)
+ *angles* list of angles of the arrows [deg/90]
+ For example, if the diagram has not been rotated,
+ an input to the top side will have an angle of 3
+ (DOWN), and an output from the top side will have
+ an angle of 1 (UP). If a flow has been skipped
+ (because its magnitude is less than *tolerance*),
+ then its angle will be *None*.
+ *tips* array in which each row is an [x, y] pair
+ indicating the positions of the tips (or "dips") of
+ the flow paths
+ If the magnitude of a flow is less the *tolerance*
+ for the instance of :class:`Sankey`, the flow is
+ skipped and its tip will be at the center of the
+ diagram.
+ *text* :class:`~matplotlib.text.Text` instance for the
+ label of the diagram
+ *texts* list of :class:`~matplotlib.text.Text` instances
+ for the labels of flows
+ =============== ===================================================
+
+ See Also
+ --------
+ Sankey.add
+ """
+ self.ax.axis([self.extent[0] - self.margin,
+ self.extent[1] + self.margin,
+ self.extent[2] - self.margin,
+ self.extent[3] + self.margin])
+ self.ax.set_aspect('equal', adjustable='datalim')
+ return self.diagrams
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/spines.py b/omnilmm/lib/python3.10/site-packages/matplotlib/spines.py
new file mode 100644
index 0000000000000000000000000000000000000000..674ae3e97067014e1e335d6efd041b9154cf873a
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/spines.py
@@ -0,0 +1,588 @@
+from collections.abc import MutableMapping
+import functools
+
+import numpy as np
+
+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
+import matplotlib.path as mpath
+
+
+class Spine(mpatches.Patch):
+ """
+ An axis spine -- the line noting the data area boundaries.
+
+ Spines are the lines connecting the axis tick marks and noting the
+ boundaries of the data area. They can be placed at arbitrary
+ positions. See `~.Spine.set_position` for more information.
+
+ The default position is ``('outward', 0)``.
+
+ Spines are subclasses of `.Patch`, and inherit much of their behavior.
+
+ Spines draw a line, a circle, or an arc depending on if
+ `~.Spine.set_patch_line`, `~.Spine.set_patch_circle`, or
+ `~.Spine.set_patch_arc` has been called. Line-like is the default.
+
+ For examples see :ref:`spines_examples`.
+ """
+ def __str__(self):
+ return "Spine"
+
+ @_docstring.dedent_interpd
+ def __init__(self, axes, spine_type, path, **kwargs):
+ """
+ Parameters
+ ----------
+ axes : `~matplotlib.axes.Axes`
+ The `~.axes.Axes` instance containing the spine.
+ spine_type : str
+ The spine type.
+ path : `~matplotlib.path.Path`
+ The `.Path` instance used to draw the spine.
+
+ Other Parameters
+ ----------------
+ **kwargs
+ Valid keyword arguments are:
+
+ %(Patch:kwdoc)s
+ """
+ super().__init__(**kwargs)
+ self.axes = axes
+ self.set_figure(self.axes.figure)
+ self.spine_type = spine_type
+ self.set_facecolor('none')
+ self.set_edgecolor(mpl.rcParams['axes.edgecolor'])
+ self.set_linewidth(mpl.rcParams['axes.linewidth'])
+ self.set_capstyle('projecting')
+ self.axis = None
+
+ self.set_zorder(2.5)
+ self.set_transform(self.axes.transData) # default transform
+
+ self._bounds = None # default bounds
+
+ # Defer initial position determination. (Not much support for
+ # non-rectangular axes is currently implemented, and this lets
+ # them pass through the spines machinery without errors.)
+ self._position = None
+ _api.check_isinstance(mpath.Path, path=path)
+ self._path = path
+
+ # To support drawing both linear and circular spines, this
+ # class implements Patch behavior three ways. If
+ # self._patch_type == 'line', behave like a mpatches.PathPatch
+ # instance. If self._patch_type == 'circle', behave like a
+ # mpatches.Ellipse instance. If self._patch_type == 'arc', behave like
+ # a mpatches.Arc instance.
+ self._patch_type = 'line'
+
+ # Behavior copied from mpatches.Ellipse:
+ # Note: This cannot be calculated until this is added to an Axes
+ self._patch_transform = mtransforms.IdentityTransform()
+
+ def set_patch_arc(self, center, radius, theta1, theta2):
+ """Set the spine to be arc-like."""
+ self._patch_type = 'arc'
+ self._center = center
+ self._width = radius * 2
+ self._height = radius * 2
+ self._theta1 = theta1
+ self._theta2 = theta2
+ self._path = mpath.Path.arc(theta1, theta2)
+ # arc drawn on axes transform
+ self.set_transform(self.axes.transAxes)
+ self.stale = True
+
+ def set_patch_circle(self, center, radius):
+ """Set the spine to be circular."""
+ self._patch_type = 'circle'
+ self._center = center
+ self._width = radius * 2
+ self._height = radius * 2
+ # circle drawn on axes transform
+ self.set_transform(self.axes.transAxes)
+ self.stale = True
+
+ def set_patch_line(self):
+ """Set the spine to be linear."""
+ self._patch_type = 'line'
+ self.stale = True
+
+ # Behavior copied from mpatches.Ellipse:
+ def _recompute_transform(self):
+ """
+ Notes
+ -----
+ This cannot be called until after this has been added to an Axes,
+ otherwise unit conversion will fail. This makes it very important to
+ call the accessor method and not directly access the transformation
+ member variable.
+ """
+ assert self._patch_type in ('arc', 'circle')
+ center = (self.convert_xunits(self._center[0]),
+ self.convert_yunits(self._center[1]))
+ width = self.convert_xunits(self._width)
+ height = self.convert_yunits(self._height)
+ self._patch_transform = mtransforms.Affine2D() \
+ .scale(width * 0.5, height * 0.5) \
+ .translate(*center)
+
+ def get_patch_transform(self):
+ if self._patch_type in ('arc', 'circle'):
+ self._recompute_transform()
+ return self._patch_transform
+ else:
+ return super().get_patch_transform()
+
+ def get_window_extent(self, renderer=None):
+ """
+ Return the window extent of the spines in display space, including
+ padding for ticks (but not their labels)
+
+ See Also
+ --------
+ matplotlib.axes.Axes.get_tightbbox
+ matplotlib.axes.Axes.get_window_extent
+ """
+ # make sure the location is updated so that transforms etc are correct:
+ self._adjust_location()
+ bb = super().get_window_extent(renderer=renderer)
+ if self.axis is None or not self.axis.get_visible():
+ return bb
+ bboxes = [bb]
+ drawn_ticks = self.axis._update_ticks()
+
+ major_tick = next(iter({*drawn_ticks} & {*self.axis.majorTicks}), None)
+ minor_tick = next(iter({*drawn_ticks} & {*self.axis.minorTicks}), None)
+ for tick in [major_tick, minor_tick]:
+ if tick is None:
+ continue
+ bb0 = bb.frozen()
+ tickl = tick._size
+ tickdir = tick._tickdir
+ if tickdir == 'out':
+ padout = 1
+ padin = 0
+ elif tickdir == 'in':
+ padout = 0
+ padin = 1
+ else:
+ padout = 0.5
+ padin = 0.5
+ padout = padout * tickl / 72 * self.figure.dpi
+ padin = padin * tickl / 72 * self.figure.dpi
+
+ if tick.tick1line.get_visible():
+ if self.spine_type == 'left':
+ bb0.x0 = bb0.x0 - padout
+ bb0.x1 = bb0.x1 + padin
+ elif self.spine_type == 'bottom':
+ bb0.y0 = bb0.y0 - padout
+ bb0.y1 = bb0.y1 + padin
+
+ if tick.tick2line.get_visible():
+ if self.spine_type == 'right':
+ bb0.x1 = bb0.x1 + padout
+ bb0.x0 = bb0.x0 - padin
+ elif self.spine_type == 'top':
+ bb0.y1 = bb0.y1 + padout
+ bb0.y0 = bb0.y0 - padout
+ bboxes.append(bb0)
+
+ return mtransforms.Bbox.union(bboxes)
+
+ def get_path(self):
+ return self._path
+
+ def _ensure_position_is_set(self):
+ if self._position is None:
+ # default position
+ self._position = ('outward', 0.0) # in points
+ self.set_position(self._position)
+
+ def register_axis(self, axis):
+ """
+ Register an axis.
+
+ An axis should be registered with its corresponding spine from
+ the Axes instance. This allows the spine to clear any axis
+ properties when needed.
+ """
+ self.axis = axis
+ if self.axis is not None:
+ self.axis.clear()
+ self.stale = True
+
+ def clear(self):
+ """Clear the current spine."""
+ self._position = None # clear position
+ if self.axis is not None:
+ self.axis.clear()
+
+ def _adjust_location(self):
+ """Automatically set spine bounds to the view interval."""
+
+ if self.spine_type == 'circle':
+ return
+
+ if self._bounds is not None:
+ low, high = self._bounds
+ elif self.spine_type in ('left', 'right'):
+ low, high = self.axes.viewLim.intervaly
+ elif self.spine_type in ('top', 'bottom'):
+ low, high = self.axes.viewLim.intervalx
+ else:
+ raise ValueError(f'unknown spine spine_type: {self.spine_type}')
+
+ if self._patch_type == 'arc':
+ if self.spine_type in ('bottom', 'top'):
+ try:
+ direction = self.axes.get_theta_direction()
+ except AttributeError:
+ direction = 1
+ try:
+ offset = self.axes.get_theta_offset()
+ except AttributeError:
+ offset = 0
+ low = low * direction + offset
+ high = high * direction + offset
+ if low > high:
+ low, high = high, low
+
+ self._path = mpath.Path.arc(np.rad2deg(low), np.rad2deg(high))
+
+ if self.spine_type == 'bottom':
+ rmin, rmax = self.axes.viewLim.intervaly
+ try:
+ rorigin = self.axes.get_rorigin()
+ except AttributeError:
+ rorigin = rmin
+ scaled_diameter = (rmin - rorigin) / (rmax - rorigin)
+ self._height = scaled_diameter
+ self._width = scaled_diameter
+
+ else:
+ raise ValueError('unable to set bounds for spine "%s"' %
+ self.spine_type)
+ else:
+ v1 = self._path.vertices
+ assert v1.shape == (2, 2), 'unexpected vertices shape'
+ if self.spine_type in ['left', 'right']:
+ v1[0, 1] = low
+ v1[1, 1] = high
+ elif self.spine_type in ['bottom', 'top']:
+ v1[0, 0] = low
+ v1[1, 0] = high
+ else:
+ raise ValueError('unable to set bounds for spine "%s"' %
+ self.spine_type)
+
+ @allow_rasterization
+ def draw(self, renderer):
+ self._adjust_location()
+ ret = super().draw(renderer)
+ self.stale = False
+ return ret
+
+ def set_position(self, position):
+ """
+ Set the position of the spine.
+
+ Spine position is specified by a 2 tuple of (position type,
+ amount). The position types are:
+
+ * 'outward': place the spine out from the data area by the specified
+ number of points. (Negative values place the spine inwards.)
+ * 'axes': place the spine at the specified Axes coordinate (0 to 1).
+ * 'data': place the spine at the specified data coordinate.
+
+ Additionally, shorthand notations define a special positions:
+
+ * 'center' -> ``('axes', 0.5)``
+ * 'zero' -> ``('data', 0.0)``
+
+ Examples
+ --------
+ :doc:`/gallery/spines/spine_placement_demo`
+ """
+ if position in ('center', 'zero'): # special positions
+ pass
+ else:
+ if len(position) != 2:
+ raise ValueError("position should be 'center' or 2-tuple")
+ if position[0] not in ['outward', 'axes', 'data']:
+ raise ValueError("position[0] should be one of 'outward', "
+ "'axes', or 'data' ")
+ self._position = position
+ self.set_transform(self.get_spine_transform())
+ if self.axis is not None:
+ self.axis.reset_ticks()
+ self.stale = True
+
+ def get_position(self):
+ """Return the spine position."""
+ self._ensure_position_is_set()
+ return self._position
+
+ def get_spine_transform(self):
+ """Return the spine transform."""
+ self._ensure_position_is_set()
+
+ position = self._position
+ if isinstance(position, str):
+ if position == 'center':
+ position = ('axes', 0.5)
+ elif position == 'zero':
+ position = ('data', 0)
+ assert len(position) == 2, 'position should be 2-tuple'
+ position_type, amount = position
+ _api.check_in_list(['axes', 'outward', 'data'],
+ position_type=position_type)
+ if self.spine_type in ['left', 'right']:
+ base_transform = self.axes.get_yaxis_transform(which='grid')
+ elif self.spine_type in ['top', 'bottom']:
+ base_transform = self.axes.get_xaxis_transform(which='grid')
+ else:
+ raise ValueError(f'unknown spine spine_type: {self.spine_type!r}')
+
+ if position_type == 'outward':
+ if amount == 0: # short circuit commonest case
+ return base_transform
+ else:
+ offset_vec = {'left': (-1, 0), 'right': (1, 0),
+ 'bottom': (0, -1), 'top': (0, 1),
+ }[self.spine_type]
+ # calculate x and y offset in dots
+ offset_dots = amount * np.array(offset_vec) / 72
+ return (base_transform
+ + mtransforms.ScaledTranslation(
+ *offset_dots, self.figure.dpi_scale_trans))
+ elif position_type == 'axes':
+ if self.spine_type in ['left', 'right']:
+ # keep y unchanged, fix x at amount
+ return (mtransforms.Affine2D.from_values(0, 0, 0, 1, amount, 0)
+ + base_transform)
+ elif self.spine_type in ['bottom', 'top']:
+ # keep x unchanged, fix y at amount
+ return (mtransforms.Affine2D.from_values(1, 0, 0, 0, 0, amount)
+ + base_transform)
+ elif position_type == 'data':
+ if self.spine_type in ('right', 'top'):
+ # The right and top spines have a default position of 1 in
+ # axes coordinates. When specifying the position in data
+ # coordinates, we need to calculate the position relative to 0.
+ amount -= 1
+ if self.spine_type in ('left', 'right'):
+ return mtransforms.blended_transform_factory(
+ mtransforms.Affine2D().translate(amount, 0)
+ + self.axes.transData,
+ self.axes.transData)
+ elif self.spine_type in ('bottom', 'top'):
+ return mtransforms.blended_transform_factory(
+ self.axes.transData,
+ mtransforms.Affine2D().translate(0, amount)
+ + self.axes.transData)
+
+ def set_bounds(self, low=None, high=None):
+ """
+ Set the spine bounds.
+
+ Parameters
+ ----------
+ low : float or None, optional
+ The lower spine bound. Passing *None* leaves the limit unchanged.
+
+ The bounds may also be passed as the tuple (*low*, *high*) as the
+ first positional argument.
+
+ .. ACCEPTS: (low: float, high: float)
+
+ high : float or None, optional
+ The higher spine bound. Passing *None* leaves the limit unchanged.
+ """
+ if self.spine_type == 'circle':
+ raise ValueError(
+ 'set_bounds() method incompatible with circular spines')
+ if high is None and np.iterable(low):
+ low, high = low
+ old_low, old_high = self.get_bounds() or (None, None)
+ if low is None:
+ low = old_low
+ if high is None:
+ high = old_high
+ self._bounds = (low, high)
+ self.stale = True
+
+ def get_bounds(self):
+ """Get the bounds of the spine."""
+ return self._bounds
+
+ @classmethod
+ def linear_spine(cls, axes, spine_type, **kwargs):
+ """Create and return a linear `Spine`."""
+ # all values of 0.999 get replaced upon call to set_bounds()
+ if spine_type == 'left':
+ path = mpath.Path([(0.0, 0.999), (0.0, 0.999)])
+ elif spine_type == 'right':
+ path = mpath.Path([(1.0, 0.999), (1.0, 0.999)])
+ elif spine_type == 'bottom':
+ path = mpath.Path([(0.999, 0.0), (0.999, 0.0)])
+ elif spine_type == 'top':
+ path = mpath.Path([(0.999, 1.0), (0.999, 1.0)])
+ else:
+ raise ValueError('unable to make path for spine "%s"' % spine_type)
+ result = cls(axes, spine_type, path, **kwargs)
+ result.set_visible(mpl.rcParams['axes.spines.{0}'.format(spine_type)])
+
+ return result
+
+ @classmethod
+ def arc_spine(cls, axes, spine_type, center, radius, theta1, theta2,
+ **kwargs):
+ """Create and return an arc `Spine`."""
+ path = mpath.Path.arc(theta1, theta2)
+ result = cls(axes, spine_type, path, **kwargs)
+ result.set_patch_arc(center, radius, theta1, theta2)
+ return result
+
+ @classmethod
+ def circular_spine(cls, axes, center, radius, **kwargs):
+ """Create and return a circular `Spine`."""
+ path = mpath.Path.unit_circle()
+ spine_type = 'circle'
+ result = cls(axes, spine_type, path, **kwargs)
+ result.set_patch_circle(center, radius)
+ return result
+
+ def set_color(self, c):
+ """
+ Set the edgecolor.
+
+ Parameters
+ ----------
+ c : color
+
+ Notes
+ -----
+ This method does not modify the facecolor (which defaults to "none"),
+ unlike the `.Patch.set_color` method defined in the parent class. Use
+ `.Patch.set_facecolor` to set the facecolor.
+ """
+ self.set_edgecolor(c)
+ self.stale = True
+
+
+class SpinesProxy:
+ """
+ A proxy to broadcast ``set_*`` method calls to all contained `.Spines`.
+
+ The proxy cannot be used for any other operations on its members.
+
+ The supported methods are determined dynamically based on the contained
+ spines. If not all spines support a given method, it's executed only on
+ the subset of spines that support it.
+ """
+ def __init__(self, spine_dict):
+ self._spine_dict = spine_dict
+
+ def __getattr__(self, name):
+ broadcast_targets = [spine for spine in self._spine_dict.values()
+ if hasattr(spine, name)]
+ if not name.startswith('set_') or not broadcast_targets:
+ raise AttributeError(
+ f"'SpinesProxy' object has no attribute '{name}'")
+
+ def x(_targets, _funcname, *args, **kwargs):
+ for spine in _targets:
+ getattr(spine, _funcname)(*args, **kwargs)
+ x = functools.partial(x, broadcast_targets, name)
+ x.__doc__ = broadcast_targets[0].__doc__
+ return x
+
+ def __dir__(self):
+ names = []
+ for spine in self._spine_dict.values():
+ names.extend(name
+ for name in dir(spine) if name.startswith('set_'))
+ return list(sorted(set(names)))
+
+
+class Spines(MutableMapping):
+ r"""
+ The container of all `.Spine`\s in an Axes.
+
+ The interface is dict-like mapping names (e.g. 'left') to `.Spine` objects.
+ Additionally, it implements some pandas.Series-like features like accessing
+ elements by attribute::
+
+ spines['top'].set_visible(False)
+ spines.top.set_visible(False)
+
+ Multiple spines can be addressed simultaneously by passing a list::
+
+ spines[['top', 'right']].set_visible(False)
+
+ Use an open slice to address all spines::
+
+ spines[:].set_visible(False)
+
+ The latter two indexing methods will return a `SpinesProxy` that broadcasts
+ all ``set_*`` calls to its members, but cannot be used for any other
+ operation.
+ """
+ def __init__(self, **kwargs):
+ self._dict = kwargs
+
+ @classmethod
+ def from_dict(cls, d):
+ return cls(**d)
+
+ def __getstate__(self):
+ return self._dict
+
+ def __setstate__(self, state):
+ self.__init__(**state)
+
+ def __getattr__(self, name):
+ try:
+ return self._dict[name]
+ except KeyError:
+ raise AttributeError(
+ f"'Spines' object does not contain a '{name}' spine")
+
+ def __getitem__(self, key):
+ if isinstance(key, list):
+ unknown_keys = [k for k in key if k not in self._dict]
+ if unknown_keys:
+ raise KeyError(', '.join(unknown_keys))
+ return SpinesProxy({k: v for k, v in self._dict.items()
+ if k in key})
+ if isinstance(key, tuple):
+ raise ValueError('Multiple spines must be passed as a single list')
+ if isinstance(key, slice):
+ if key.start is None and key.stop is None and key.step is None:
+ return SpinesProxy(self._dict)
+ else:
+ raise ValueError(
+ 'Spines does not support slicing except for the fully '
+ 'open slice [:] to access all spines.')
+ return self._dict[key]
+
+ def __setitem__(self, key, value):
+ # TODO: Do we want to deprecate adding spines?
+ self._dict[key] = value
+
+ def __delitem__(self, key):
+ # TODO: Do we want to deprecate deleting spines?
+ del self._dict[key]
+
+ def __iter__(self):
+ return iter(self._dict)
+
+ def __len__(self):
+ return len(self._dict)
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/streamplot.py b/omnilmm/lib/python3.10/site-packages/matplotlib/streamplot.py
new file mode 100644
index 0000000000000000000000000000000000000000..293fd679121354e6ea299f1a786c326582c12cd7
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/streamplot.py
@@ -0,0 +1,707 @@
+"""
+Streamline plotting for 2D vector fields.
+
+"""
+
+import numpy as np
+
+import matplotlib as mpl
+from matplotlib import _api, cm, patches
+import matplotlib.colors as mcolors
+import matplotlib.collections as mcollections
+import matplotlib.lines as mlines
+
+
+__all__ = ['streamplot']
+
+
+def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None,
+ cmap=None, norm=None, arrowsize=1, arrowstyle='-|>',
+ minlength=0.1, transform=None, zorder=None, start_points=None,
+ maxlength=4.0, integration_direction='both',
+ broken_streamlines=True):
+ """
+ Draw streamlines of a vector flow.
+
+ Parameters
+ ----------
+ x, y : 1D/2D arrays
+ Evenly spaced strictly increasing arrays to make a grid. If 2D, all
+ rows of *x* must be equal and all columns of *y* must be equal; i.e.,
+ they must be as if generated by ``np.meshgrid(x_1d, y_1d)``.
+ u, v : 2D arrays
+ *x* and *y*-velocities. The number of rows and columns must match
+ the length of *y* and *x*, respectively.
+ density : float or (float, float)
+ Controls the closeness of streamlines. When ``density = 1``, the domain
+ is divided into a 30x30 grid. *density* linearly scales this grid.
+ Each cell in the grid can have, at most, one traversing streamline.
+ For different densities in each direction, use a tuple
+ (density_x, density_y).
+ linewidth : float or 2D array
+ The width of the streamlines. With a 2D array the line width can be
+ varied across the grid. The array must have the same shape as *u*
+ and *v*.
+ color : color or 2D array
+ The streamline color. If given an array, its values are converted to
+ colors using *cmap* and *norm*. The array must have the same shape
+ as *u* and *v*.
+ cmap, norm
+ Data normalization and colormapping parameters for *color*; only used
+ if *color* is an array of floats. See `~.Axes.imshow` for a detailed
+ description.
+ arrowsize : float
+ Scaling factor for the arrow size.
+ arrowstyle : str
+ Arrow style specification.
+ See `~matplotlib.patches.FancyArrowPatch`.
+ minlength : float
+ Minimum length of streamline in axes coordinates.
+ start_points : Nx2 array
+ Coordinates of starting points for the streamlines in data coordinates
+ (the same coordinates as the *x* and *y* arrays).
+ zorder : float
+ The zorder of the streamlines and arrows.
+ Artists with lower zorder values are drawn first.
+ maxlength : float
+ Maximum length of streamline in axes coordinates.
+ integration_direction : {'forward', 'backward', 'both'}, default: 'both'
+ Integrate the streamline in forward, backward or both directions.
+ data : indexable object, optional
+ DATA_PARAMETER_PLACEHOLDER
+ broken_streamlines : boolean, default: True
+ If False, forces streamlines to continue until they
+ leave the plot domain. If True, they may be terminated if they
+ come too close to another streamline.
+
+ Returns
+ -------
+ StreamplotSet
+ Container object with attributes
+
+ - ``lines``: `.LineCollection` of streamlines
+
+ - ``arrows``: `.PatchCollection` containing `.FancyArrowPatch`
+ objects representing the arrows half-way along streamlines.
+
+ This container will probably change in the future to allow changes
+ to the colormap, alpha, etc. for both lines and arrows, but these
+ changes should be backward compatible.
+ """
+ grid = Grid(x, y)
+ mask = StreamMask(density)
+ dmap = DomainMap(grid, mask)
+
+ if zorder is None:
+ zorder = mlines.Line2D.zorder
+
+ # default to data coordinates
+ if transform is None:
+ transform = axes.transData
+
+ if color is None:
+ color = axes._get_lines.get_next_color()
+
+ if linewidth is None:
+ linewidth = mpl.rcParams['lines.linewidth']
+
+ line_kw = {}
+ arrow_kw = dict(arrowstyle=arrowstyle, mutation_scale=10 * arrowsize)
+
+ _api.check_in_list(['both', 'forward', 'backward'],
+ integration_direction=integration_direction)
+
+ if integration_direction == 'both':
+ maxlength /= 2.
+
+ use_multicolor_lines = isinstance(color, np.ndarray)
+ if use_multicolor_lines:
+ if color.shape != grid.shape:
+ raise ValueError("If 'color' is given, it must match the shape of "
+ "the (x, y) grid")
+ line_colors = [[]] # Empty entry allows concatenation of zero arrays.
+ color = np.ma.masked_invalid(color)
+ else:
+ line_kw['color'] = color
+ arrow_kw['color'] = color
+
+ if isinstance(linewidth, np.ndarray):
+ if linewidth.shape != grid.shape:
+ raise ValueError("If 'linewidth' is given, it must match the "
+ "shape of the (x, y) grid")
+ line_kw['linewidth'] = []
+ else:
+ line_kw['linewidth'] = linewidth
+ arrow_kw['linewidth'] = linewidth
+
+ line_kw['zorder'] = zorder
+ arrow_kw['zorder'] = zorder
+
+ # Sanity checks.
+ if u.shape != grid.shape or v.shape != grid.shape:
+ raise ValueError("'u' and 'v' must match the shape of the (x, y) grid")
+
+ u = np.ma.masked_invalid(u)
+ v = np.ma.masked_invalid(v)
+
+ integrate = _get_integrator(u, v, dmap, minlength, maxlength,
+ integration_direction)
+
+ trajectories = []
+ if start_points is None:
+ for xm, ym in _gen_starting_points(mask.shape):
+ if mask[ym, xm] == 0:
+ xg, yg = dmap.mask2grid(xm, ym)
+ t = integrate(xg, yg, broken_streamlines)
+ if t is not None:
+ trajectories.append(t)
+ else:
+ sp2 = np.asanyarray(start_points, dtype=float).copy()
+
+ # Check if start_points are outside the data boundaries
+ for xs, ys in sp2:
+ if not (grid.x_origin <= xs <= grid.x_origin + grid.width and
+ grid.y_origin <= ys <= grid.y_origin + grid.height):
+ raise ValueError("Starting point ({}, {}) outside of data "
+ "boundaries".format(xs, ys))
+
+ # Convert start_points from data to array coords
+ # Shift the seed points from the bottom left of the data so that
+ # data2grid works properly.
+ sp2[:, 0] -= grid.x_origin
+ sp2[:, 1] -= grid.y_origin
+
+ for xs, ys in sp2:
+ xg, yg = dmap.data2grid(xs, ys)
+ # Floating point issues can cause xg, yg to be slightly out of
+ # bounds for xs, ys on the upper boundaries. Because we have
+ # already checked that the starting points are within the original
+ # grid, clip the xg, yg to the grid to work around this issue
+ xg = np.clip(xg, 0, grid.nx - 1)
+ yg = np.clip(yg, 0, grid.ny - 1)
+
+ t = integrate(xg, yg, broken_streamlines)
+ if t is not None:
+ trajectories.append(t)
+
+ if use_multicolor_lines:
+ if norm is None:
+ norm = mcolors.Normalize(color.min(), color.max())
+ cmap = cm._ensure_cmap(cmap)
+
+ streamlines = []
+ arrows = []
+ for t in trajectories:
+ tgx, tgy = t.T
+ # Rescale from grid-coordinates to data-coordinates.
+ tx, ty = dmap.grid2data(tgx, tgy)
+ tx += grid.x_origin
+ ty += grid.y_origin
+
+ points = np.transpose([tx, ty]).reshape(-1, 1, 2)
+ streamlines.extend(np.hstack([points[:-1], points[1:]]))
+
+ # Add arrows halfway along each trajectory.
+ s = np.cumsum(np.hypot(np.diff(tx), np.diff(ty)))
+ n = np.searchsorted(s, s[-1] / 2.)
+ arrow_tail = (tx[n], ty[n])
+ arrow_head = (np.mean(tx[n:n + 2]), np.mean(ty[n:n + 2]))
+
+ if isinstance(linewidth, np.ndarray):
+ line_widths = interpgrid(linewidth, tgx, tgy)[:-1]
+ line_kw['linewidth'].extend(line_widths)
+ arrow_kw['linewidth'] = line_widths[n]
+
+ if use_multicolor_lines:
+ color_values = interpgrid(color, tgx, tgy)[:-1]
+ line_colors.append(color_values)
+ arrow_kw['color'] = cmap(norm(color_values[n]))
+
+ p = patches.FancyArrowPatch(
+ arrow_tail, arrow_head, transform=transform, **arrow_kw)
+ arrows.append(p)
+
+ lc = mcollections.LineCollection(
+ streamlines, transform=transform, **line_kw)
+ lc.sticky_edges.x[:] = [grid.x_origin, grid.x_origin + grid.width]
+ lc.sticky_edges.y[:] = [grid.y_origin, grid.y_origin + grid.height]
+ if use_multicolor_lines:
+ lc.set_array(np.ma.hstack(line_colors))
+ lc.set_cmap(cmap)
+ lc.set_norm(norm)
+ axes.add_collection(lc)
+
+ ac = mcollections.PatchCollection(arrows)
+ # Adding the collection itself is broken; see #2341.
+ for p in arrows:
+ axes.add_patch(p)
+
+ axes.autoscale_view()
+ stream_container = StreamplotSet(lc, ac)
+ return stream_container
+
+
+class StreamplotSet:
+
+ def __init__(self, lines, arrows):
+ self.lines = lines
+ self.arrows = arrows
+
+
+# Coordinate definitions
+# ========================
+
+class DomainMap:
+ """
+ Map representing different coordinate systems.
+
+ Coordinate definitions:
+
+ * axes-coordinates goes from 0 to 1 in the domain.
+ * data-coordinates are specified by the input x-y coordinates.
+ * grid-coordinates goes from 0 to N and 0 to M for an N x M grid,
+ where N and M match the shape of the input data.
+ * mask-coordinates goes from 0 to N and 0 to M for an N x M mask,
+ where N and M are user-specified to control the density of streamlines.
+
+ This class also has methods for adding trajectories to the StreamMask.
+ Before adding a trajectory, run `start_trajectory` to keep track of regions
+ crossed by a given trajectory. Later, if you decide the trajectory is bad
+ (e.g., if the trajectory is very short) just call `undo_trajectory`.
+ """
+
+ def __init__(self, grid, mask):
+ self.grid = grid
+ self.mask = mask
+ # Constants for conversion between grid- and mask-coordinates
+ self.x_grid2mask = (mask.nx - 1) / (grid.nx - 1)
+ self.y_grid2mask = (mask.ny - 1) / (grid.ny - 1)
+
+ self.x_mask2grid = 1. / self.x_grid2mask
+ self.y_mask2grid = 1. / self.y_grid2mask
+
+ self.x_data2grid = 1. / grid.dx
+ self.y_data2grid = 1. / grid.dy
+
+ def grid2mask(self, xi, yi):
+ """Return nearest space in mask-coords from given grid-coords."""
+ return round(xi * self.x_grid2mask), round(yi * self.y_grid2mask)
+
+ def mask2grid(self, xm, ym):
+ return xm * self.x_mask2grid, ym * self.y_mask2grid
+
+ def data2grid(self, xd, yd):
+ return xd * self.x_data2grid, yd * self.y_data2grid
+
+ def grid2data(self, xg, yg):
+ return xg / self.x_data2grid, yg / self.y_data2grid
+
+ def start_trajectory(self, xg, yg, broken_streamlines=True):
+ xm, ym = self.grid2mask(xg, yg)
+ self.mask._start_trajectory(xm, ym, broken_streamlines)
+
+ def reset_start_point(self, xg, yg):
+ xm, ym = self.grid2mask(xg, yg)
+ self.mask._current_xy = (xm, ym)
+
+ def update_trajectory(self, xg, yg, broken_streamlines=True):
+ if not self.grid.within_grid(xg, yg):
+ raise InvalidIndexError
+ xm, ym = self.grid2mask(xg, yg)
+ self.mask._update_trajectory(xm, ym, broken_streamlines)
+
+ def undo_trajectory(self):
+ self.mask._undo_trajectory()
+
+
+class Grid:
+ """Grid of data."""
+ def __init__(self, x, y):
+
+ if np.ndim(x) == 1:
+ pass
+ elif np.ndim(x) == 2:
+ x_row = x[0]
+ if not np.allclose(x_row, x):
+ raise ValueError("The rows of 'x' must be equal")
+ x = x_row
+ else:
+ raise ValueError("'x' can have at maximum 2 dimensions")
+
+ if np.ndim(y) == 1:
+ pass
+ elif np.ndim(y) == 2:
+ yt = np.transpose(y) # Also works for nested lists.
+ y_col = yt[0]
+ if not np.allclose(y_col, yt):
+ raise ValueError("The columns of 'y' must be equal")
+ y = y_col
+ else:
+ raise ValueError("'y' can have at maximum 2 dimensions")
+
+ if not (np.diff(x) > 0).all():
+ raise ValueError("'x' must be strictly increasing")
+ if not (np.diff(y) > 0).all():
+ raise ValueError("'y' must be strictly increasing")
+
+ self.nx = len(x)
+ self.ny = len(y)
+
+ self.dx = x[1] - x[0]
+ self.dy = y[1] - y[0]
+
+ self.x_origin = x[0]
+ self.y_origin = y[0]
+
+ self.width = x[-1] - x[0]
+ self.height = y[-1] - y[0]
+
+ if not np.allclose(np.diff(x), self.width / (self.nx - 1)):
+ raise ValueError("'x' values must be equally spaced")
+ if not np.allclose(np.diff(y), self.height / (self.ny - 1)):
+ raise ValueError("'y' values must be equally spaced")
+
+ @property
+ def shape(self):
+ return self.ny, self.nx
+
+ def within_grid(self, xi, yi):
+ """Return whether (*xi*, *yi*) is a valid index of the grid."""
+ # Note that xi/yi can be floats; so, for example, we can't simply check
+ # `xi < self.nx` since *xi* can be `self.nx - 1 < xi < self.nx`
+ return 0 <= xi <= self.nx - 1 and 0 <= yi <= self.ny - 1
+
+
+class StreamMask:
+ """
+ Mask to keep track of discrete regions crossed by streamlines.
+
+ The resolution of this grid determines the approximate spacing between
+ trajectories. Streamlines are only allowed to pass through zeroed cells:
+ When a streamline enters a cell, that cell is set to 1, and no new
+ streamlines are allowed to enter.
+ """
+
+ def __init__(self, density):
+ try:
+ self.nx, self.ny = (30 * np.broadcast_to(density, 2)).astype(int)
+ except ValueError as err:
+ raise ValueError("'density' must be a scalar or be of length "
+ "2") from err
+ if self.nx < 0 or self.ny < 0:
+ raise ValueError("'density' must be positive")
+ self._mask = np.zeros((self.ny, self.nx))
+ self.shape = self._mask.shape
+
+ self._current_xy = None
+
+ def __getitem__(self, args):
+ return self._mask[args]
+
+ def _start_trajectory(self, xm, ym, broken_streamlines=True):
+ """Start recording streamline trajectory"""
+ self._traj = []
+ self._update_trajectory(xm, ym, broken_streamlines)
+
+ def _undo_trajectory(self):
+ """Remove current trajectory from mask"""
+ for t in self._traj:
+ self._mask[t] = 0
+
+ def _update_trajectory(self, xm, ym, broken_streamlines=True):
+ """
+ Update current trajectory position in mask.
+
+ If the new position has already been filled, raise `InvalidIndexError`.
+ """
+ if self._current_xy != (xm, ym):
+ if self[ym, xm] == 0:
+ self._traj.append((ym, xm))
+ self._mask[ym, xm] = 1
+ self._current_xy = (xm, ym)
+ else:
+ if broken_streamlines:
+ raise InvalidIndexError
+ else:
+ pass
+
+
+class InvalidIndexError(Exception):
+ pass
+
+
+class TerminateTrajectory(Exception):
+ pass
+
+
+# Integrator definitions
+# =======================
+
+def _get_integrator(u, v, dmap, minlength, maxlength, integration_direction):
+
+ # rescale velocity onto grid-coordinates for integrations.
+ u, v = dmap.data2grid(u, v)
+
+ # speed (path length) will be in axes-coordinates
+ u_ax = u / (dmap.grid.nx - 1)
+ v_ax = v / (dmap.grid.ny - 1)
+ speed = np.ma.sqrt(u_ax ** 2 + v_ax ** 2)
+
+ def forward_time(xi, yi):
+ if not dmap.grid.within_grid(xi, yi):
+ raise OutOfBounds
+ ds_dt = interpgrid(speed, xi, yi)
+ if ds_dt == 0:
+ raise TerminateTrajectory()
+ dt_ds = 1. / ds_dt
+ ui = interpgrid(u, xi, yi)
+ vi = interpgrid(v, xi, yi)
+ return ui * dt_ds, vi * dt_ds
+
+ def backward_time(xi, yi):
+ dxi, dyi = forward_time(xi, yi)
+ return -dxi, -dyi
+
+ def integrate(x0, y0, broken_streamlines=True):
+ """
+ Return x, y grid-coordinates of trajectory based on starting point.
+
+ Integrate both forward and backward in time from starting point in
+ grid coordinates.
+
+ Integration is terminated when a trajectory reaches a domain boundary
+ or when it crosses into an already occupied cell in the StreamMask. The
+ resulting trajectory is None if it is shorter than `minlength`.
+ """
+
+ stotal, xy_traj = 0., []
+
+ try:
+ dmap.start_trajectory(x0, y0, broken_streamlines)
+ except InvalidIndexError:
+ return None
+ if integration_direction in ['both', 'backward']:
+ s, xyt = _integrate_rk12(x0, y0, dmap, backward_time, maxlength,
+ broken_streamlines)
+ stotal += s
+ xy_traj += xyt[::-1]
+
+ if integration_direction in ['both', 'forward']:
+ dmap.reset_start_point(x0, y0)
+ s, xyt = _integrate_rk12(x0, y0, dmap, forward_time, maxlength,
+ broken_streamlines)
+ stotal += s
+ xy_traj += xyt[1:]
+
+ if stotal > minlength:
+ return np.broadcast_arrays(xy_traj, np.empty((1, 2)))[0]
+ else: # reject short trajectories
+ dmap.undo_trajectory()
+ return None
+
+ return integrate
+
+
+class OutOfBounds(IndexError):
+ pass
+
+
+def _integrate_rk12(x0, y0, dmap, f, maxlength, broken_streamlines=True):
+ """
+ 2nd-order Runge-Kutta algorithm with adaptive step size.
+
+ This method is also referred to as the improved Euler's method, or Heun's
+ method. This method is favored over higher-order methods because:
+
+ 1. To get decent looking trajectories and to sample every mask cell
+ on the trajectory we need a small timestep, so a lower order
+ solver doesn't hurt us unless the data is *very* high resolution.
+ In fact, for cases where the user inputs
+ data smaller or of similar grid size to the mask grid, the higher
+ order corrections are negligible because of the very fast linear
+ interpolation used in `interpgrid`.
+
+ 2. For high resolution input data (i.e. beyond the mask
+ resolution), we must reduce the timestep. Therefore, an adaptive
+ timestep is more suited to the problem as this would be very hard
+ to judge automatically otherwise.
+
+ This integrator is about 1.5 - 2x as fast as RK4 and RK45 solvers (using
+ similar Python implementations) in most setups.
+ """
+ # This error is below that needed to match the RK4 integrator. It
+ # is set for visual reasons -- too low and corners start
+ # appearing ugly and jagged. Can be tuned.
+ maxerror = 0.003
+
+ # This limit is important (for all integrators) to avoid the
+ # trajectory skipping some mask cells. We could relax this
+ # condition if we use the code which is commented out below to
+ # increment the location gradually. However, due to the efficient
+ # nature of the interpolation, this doesn't boost speed by much
+ # for quite a bit of complexity.
+ maxds = min(1. / dmap.mask.nx, 1. / dmap.mask.ny, 0.1)
+
+ ds = maxds
+ stotal = 0
+ xi = x0
+ yi = y0
+ xyf_traj = []
+
+ while True:
+ try:
+ if dmap.grid.within_grid(xi, yi):
+ xyf_traj.append((xi, yi))
+ else:
+ raise OutOfBounds
+
+ # Compute the two intermediate gradients.
+ # f should raise OutOfBounds if the locations given are
+ # outside the grid.
+ k1x, k1y = f(xi, yi)
+ k2x, k2y = f(xi + ds * k1x, yi + ds * k1y)
+
+ except OutOfBounds:
+ # Out of the domain during this step.
+ # Take an Euler step to the boundary to improve neatness
+ # unless the trajectory is currently empty.
+ if xyf_traj:
+ ds, xyf_traj = _euler_step(xyf_traj, dmap, f)
+ stotal += ds
+ break
+ except TerminateTrajectory:
+ break
+
+ dx1 = ds * k1x
+ dy1 = ds * k1y
+ dx2 = ds * 0.5 * (k1x + k2x)
+ dy2 = ds * 0.5 * (k1y + k2y)
+
+ ny, nx = dmap.grid.shape
+ # Error is normalized to the axes coordinates
+ error = np.hypot((dx2 - dx1) / (nx - 1), (dy2 - dy1) / (ny - 1))
+
+ # Only save step if within error tolerance
+ if error < maxerror:
+ xi += dx2
+ yi += dy2
+ try:
+ dmap.update_trajectory(xi, yi, broken_streamlines)
+ except InvalidIndexError:
+ break
+ if stotal + ds > maxlength:
+ break
+ stotal += ds
+
+ # recalculate stepsize based on step error
+ if error == 0:
+ ds = maxds
+ else:
+ ds = min(maxds, 0.85 * ds * (maxerror / error) ** 0.5)
+
+ return stotal, xyf_traj
+
+
+def _euler_step(xyf_traj, dmap, f):
+ """Simple Euler integration step that extends streamline to boundary."""
+ ny, nx = dmap.grid.shape
+ xi, yi = xyf_traj[-1]
+ cx, cy = f(xi, yi)
+ if cx == 0:
+ dsx = np.inf
+ elif cx < 0:
+ dsx = xi / -cx
+ else:
+ dsx = (nx - 1 - xi) / cx
+ if cy == 0:
+ dsy = np.inf
+ elif cy < 0:
+ dsy = yi / -cy
+ else:
+ dsy = (ny - 1 - yi) / cy
+ ds = min(dsx, dsy)
+ xyf_traj.append((xi + cx * ds, yi + cy * ds))
+ return ds, xyf_traj
+
+
+# Utility functions
+# ========================
+
+def interpgrid(a, xi, yi):
+ """Fast 2D, linear interpolation on an integer grid"""
+
+ Ny, Nx = np.shape(a)
+ if isinstance(xi, np.ndarray):
+ x = xi.astype(int)
+ y = yi.astype(int)
+ # Check that xn, yn don't exceed max index
+ xn = np.clip(x + 1, 0, Nx - 1)
+ yn = np.clip(y + 1, 0, Ny - 1)
+ else:
+ x = int(xi)
+ y = int(yi)
+ # conditional is faster than clipping for integers
+ if x == (Nx - 1):
+ xn = x
+ else:
+ xn = x + 1
+ if y == (Ny - 1):
+ yn = y
+ else:
+ yn = y + 1
+
+ a00 = a[y, x]
+ a01 = a[y, xn]
+ a10 = a[yn, x]
+ a11 = a[yn, xn]
+ xt = xi - x
+ yt = yi - y
+ a0 = a00 * (1 - xt) + a01 * xt
+ a1 = a10 * (1 - xt) + a11 * xt
+ ai = a0 * (1 - yt) + a1 * yt
+
+ if not isinstance(xi, np.ndarray):
+ if np.ma.is_masked(ai):
+ raise TerminateTrajectory
+
+ return ai
+
+
+def _gen_starting_points(shape):
+ """
+ Yield starting points for streamlines.
+
+ Trying points on the boundary first gives higher quality streamlines.
+ This algorithm starts with a point on the mask corner and spirals inward.
+ This algorithm is inefficient, but fast compared to rest of streamplot.
+ """
+ ny, nx = shape
+ xfirst = 0
+ yfirst = 1
+ xlast = nx - 1
+ ylast = ny - 1
+ x, y = 0, 0
+ direction = 'right'
+ for i in range(nx * ny):
+ yield x, y
+
+ if direction == 'right':
+ x += 1
+ if x >= xlast:
+ xlast -= 1
+ direction = 'up'
+ elif direction == 'up':
+ y += 1
+ if y >= ylast:
+ ylast -= 1
+ direction = 'left'
+ elif direction == 'left':
+ x -= 1
+ if x <= xfirst:
+ xfirst += 1
+ direction = 'down'
+ elif direction == 'down':
+ y -= 1
+ if y <= yfirst:
+ yfirst += 1
+ direction = 'right'
diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/style/core.py b/omnilmm/lib/python3.10/site-packages/matplotlib/style/core.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ff4618ca6a3d6c10cf29c197af3a640db9a3856
--- /dev/null
+++ b/omnilmm/lib/python3.10/site-packages/matplotlib/style/core.py
@@ -0,0 +1,283 @@
+"""
+Core functions and attributes for the matplotlib style library:
+
+``use``
+ Select style sheet to override the current matplotlib settings.
+``context``
+ Context manager to use a style sheet temporarily.
+``available``
+ List available style sheets.
+``library``
+ A dictionary of style names and matplotlib settings.
+"""
+
+import contextlib
+import logging
+import os
+from pathlib import Path
+import sys
+import warnings
+
+if sys.version_info >= (3, 10):
+ import importlib.resources as importlib_resources
+else:
+ # Even though Py3.9 has importlib.resources, it doesn't properly handle
+ # modules added in sys.path.
+ import importlib_resources
+
+import matplotlib as mpl
+from matplotlib import _api, _docstring, _rc_params_in_file, rcParamsDefault
+
+_log = logging.getLogger(__name__)
+
+__all__ = ['use', 'context', 'available', 'library', 'reload_library']
+
+
+BASE_LIBRARY_PATH = os.path.join(mpl.get_data_path(), 'stylelib')
+# Users may want multiple library paths, so store a list of paths.
+USER_LIBRARY_PATHS = [os.path.join(mpl.get_configdir(), 'stylelib')]
+STYLE_EXTENSION = 'mplstyle'
+# A list of rcParams that should not be applied from styles
+STYLE_BLACKLIST = {
+ 'interactive', 'backend', 'webagg.port', 'webagg.address',
+ 'webagg.port_retries', 'webagg.open_in_browser', 'backend_fallback',
+ 'toolbar', 'timezone', 'figure.max_open_warning',
+ 'figure.raise_window', 'savefig.directory', 'tk.window_focus',
+ 'docstring.hardcopy', 'date.epoch'}
+_DEPRECATED_SEABORN_STYLES = {
+ s: s.replace("seaborn", "seaborn-v0_8")
+ for s in [
+ "seaborn",
+ "seaborn-bright",
+ "seaborn-colorblind",
+ "seaborn-dark",
+ "seaborn-darkgrid",
+ "seaborn-dark-palette",
+ "seaborn-deep",
+ "seaborn-muted",
+ "seaborn-notebook",
+ "seaborn-paper",
+ "seaborn-pastel",
+ "seaborn-poster",
+ "seaborn-talk",
+ "seaborn-ticks",
+ "seaborn-white",
+ "seaborn-whitegrid",
+ ]
+}
+_DEPRECATED_SEABORN_MSG = (
+ "The seaborn styles shipped by Matplotlib are deprecated since %(since)s, "
+ "as they no longer correspond to the styles shipped by seaborn. However, "
+ "they will remain available as 'seaborn-v0_8-