matplotlib.cbook

A collection of utility functions and classes. Originally, many (but not all) were from the Python Cookbook -- hence the name cbook.

This module is safe to import from anywhere within Matplotlib; it imports Matplotlib only at runtime.

class matplotlib.cbook.CallbackRegistry(exception_handler=<function _exception_printer>)[source]

Bases: object

Handle registering and disconnecting for a set of signals and callbacks:

>>> def oneat(x):
...    print('eat', x)
>>> def ondrink(x):
...    print('drink', x)
>>> from matplotlib.cbook import CallbackRegistry
>>> callbacks = CallbackRegistry()
>>> id_eat = callbacks.connect('eat', oneat)
>>> id_drink = callbacks.connect('drink', ondrink)
>>> callbacks.process('drink', 123)
drink 123
>>> callbacks.process('eat', 456)
eat 456
>>> callbacks.process('be merry', 456) # nothing will be called
>>> callbacks.disconnect(id_eat)
>>> callbacks.process('eat', 456)      # nothing will be called

In practice, one should always disconnect all callbacks when they are no longer needed to avoid dangling references (and thus memory leaks). However, real code in Matplotlib rarely does so, and due to its design, it is rather difficult to place this kind of code. To get around this, and prevent this class of memory leaks, we instead store weak references to bound methods only, so when the destination object needs to die, the CallbackRegistry won't keep it alive.

Parameters:
exception_handlercallable, optional

If provided must have signature

def handler(exc: Exception) -> None:

If not None this function will be called with any Exception subclass raised by the callbacks in CallbackRegistry.process. The handler may either consume the exception or re-raise.

The callable must be pickle-able.

The default handler is

def h(exc):
    traceback.print_exc()
connect(s, func)[source]

Register func to be called when signal s is generated.

disconnect(cid)[source]

Disconnect the callback registered with callback id cid.

process(s, *args, **kwargs)[source]

Process signal s.

All of the functions registered to receive callbacks on s will be called with *args and **kwargs.

class matplotlib.cbook.Grouper(init=())[source]

Bases: object

A disjoint-set data structure.

Objects can be joined using join(), tested for connectedness using joined(), and all disjoint sets can be retrieved by using the object as an iterator.

The objects being joined must be hashable and weak-referenceable.

Examples

>>> from matplotlib.cbook import Grouper
>>> class Foo:
...     def __init__(self, s):
...         self.s = s
...     def __repr__(self):
...         return self.s
...
>>> a, b, c, d, e, f = [Foo(x) for x in 'abcdef']
>>> grp = Grouper()
>>> grp.join(a, b)
>>> grp.join(b, c)
>>> grp.join(d, e)
>>> sorted(map(tuple, grp))
[(a, b, c), (d, e)]
>>> grp.joined(a, b)
True
>>> grp.joined(a, c)
True
>>> grp.joined(a, d)
False
clean()[source]

Clean dead weak references from the dictionary.

get_siblings(a)[source]

Return all of the items joined with a, including itself.

join(a, *args)[source]

Join given arguments into the same set. Accepts one or more arguments.

joined(a, b)[source]

Return whether a and b are members of the same set.

remove(a)[source]
exception matplotlib.cbook.IgnoredKeywordWarning(*args, **kwargs)[source]

Bases: UserWarning

[Deprecated] A class for issuing warnings about keyword arguments that will be ignored by Matplotlib.

Notes

Deprecated since version 3.3.

class matplotlib.cbook.Stack(default=None)[source]

Bases: object

Stack of elements with a movable cursor.

Mimics home/back/forward in a web browser.

back()[source]

Move the position back and return the current element.

bubble(o)[source]

Raise all references of o to the top of the stack, and return it.

Raises:
ValueError

If o is not in the stack.

clear()[source]

Empty the stack.

empty()[source]

Return whether the stack is empty.

forward()[source]

Move the position forward and return the current element.

home()[source]

Push the first element onto the top of the stack.

The first element is returned.

push(o)[source]

Push o to the stack at current position. Discard all later elements.

o is returned.

remove(o)[source]

Remove o from the stack.

Raises:
ValueError

If o is not in the stack.

matplotlib.cbook.boxplot_stats(X, whis=1.5, bootstrap=None, labels=None, autorange=False)[source]

Return a list of dictionaries of statistics used to draw a series of box and whisker plots using bxp.

Parameters:
Xarray-like

Data that will be represented in the boxplots. Should have 2 or fewer dimensions.

whisfloat or (float, float), default: 1.5

The position of the whiskers.

If a float, the lower whisker is at the lowest datum above Q1 - whis*(Q3-Q1), and the upper whisker at the highest datum below Q3 + whis*(Q3-Q1), where Q1 and Q3 are the first and third quartiles. The default value of whis = 1.5 corresponds to Tukey's original definition of boxplots.

If a pair of floats, they indicate the percentiles at which to draw the whiskers (e.g., (5, 95)). In particular, setting this to (0, 100) results in whiskers covering the whole range of the data. "range" is a deprecated synonym for (0, 100).

In the edge case where Q1 == Q3, whis is automatically set to (0, 100) (cover the whole range of the data) if autorange is True.

Beyond the whiskers, data are considered outliers and are plotted as individual points.

bootstrapint, optional

Number of times the confidence intervals around the median should be bootstrapped (percentile method).

labelsarray-like, optional

Labels for each dataset. Length must be compatible with dimensions of X.

autorangebool, optional (False)

When True and the data are distributed such that the 25th and 75th percentiles are equal, whis is set to (0, 100) such that the whisker ends are at the minimum and maximum of the data.

Returns:
list of dict

A list of dictionaries containing the results for each column of data. Keys of each dictionary are the following:

Key Value Description
label tick label for the boxplot
mean arithmetic mean value
med 50th percentile
q1 first quartile (25th percentile)
q3 third quartile (75th percentile)
cilo lower notch around the median
cihi upper notch around the median
whislo end of the lower whisker
whishi end of the upper whisker
fliers outliers

Notes

Non-bootstrapping approach to confidence interval uses Gaussian-based asymptotic approximation:

\[\mathrm{med} \pm 1.57 \times \frac{\mathrm{iqr}}{\sqrt{N}}\]

General approach from: McGill, R., Tukey, J.W., and Larsen, W.A. (1978) "Variations of Boxplots", The American Statistician, 32:12-16.

matplotlib.cbook.contiguous_regions(mask)[source]

Return a list of (ind0, ind1) such that mask[ind0:ind1].all() is True and we cover all such regions.

matplotlib.cbook.delete_masked_points(*args)[source]

Find all masked and/or non-finite points in a set of arguments, and return the arguments with only the unmasked points remaining.

Arguments can be in any of 5 categories:

  1. 1-D masked arrays
  2. 1-D ndarrays
  3. ndarrays with more than one dimension
  4. other non-string iterables
  5. anything else

The first argument must be in one of the first four categories; any argument with a length differing from that of the first argument (and hence anything in category 5) then will be passed through unchanged.

Masks are obtained from all arguments of the correct length in categories 1, 2, and 4; a point is bad if masked in a masked array or if it is a nan or inf. No attempt is made to extract a mask from categories 2, 3, and 4 if numpy.isfinite does not yield a Boolean array.

All input arguments that are not passed unchanged are returned as ndarrays after removing the points or rows corresponding to masks in any of the arguments.

A vastly simpler version of this function was originally written as a helper for Axes.scatter().

matplotlib.cbook.file_requires_unicode(x)[source]

Return whether the given writable file-like object requires Unicode to be written to it.

matplotlib.cbook.flatten(seq, scalarp=<function is_scalar_or_string>)[source]

Return a generator of flattened nested containers.

For example:

>>> from matplotlib.cbook import flatten
>>> l = (('John', ['Hunter']), (1, 23), [[([42, (5, 23)], )]])
>>> print(list(flatten(l)))
['John', 'Hunter', 1, 23, 42, 5, 23]

By: Composite of Holger Krekel and Luther Blissett From: https://code.activestate.com/recipes/121294/ and Recipe 1.12 in cookbook

matplotlib.cbook.get_realpath_and_stat(path)[source]

[Deprecated]

Notes

Deprecated since version 3.3:

matplotlib.cbook.get_sample_data(fname, asfileobj=True, *, np_load=False)[source]

Return a sample data file. fname is a path relative to the mpl-data/sample_data directory. If asfileobj is True return a file object, otherwise just a file path.

Sample data files are stored in the 'mpl-data/sample_data' directory within the Matplotlib package.

If the filename ends in .gz, the file is implicitly ungzipped. If the filename ends with .npy or .npz, asfileobj is True, and np_load is True, the file is loaded with numpy.load. np_load currently defaults to False but will default to True in a future release.

matplotlib.cbook.index_of(y)[source]

A helper function to create reasonable x values for the given y.

This is used for plotting (x, y) if x values are not explicitly given.

First try y.index (assuming y is a pandas.Series), if that fails, use range(len(y)).

This will be extended in the future to deal with more types of labeled data.

Parameters:
yfloat or array-like
Returns:
x, yndarray

The x and y values to plot.

matplotlib.cbook.is_math_text(s)[source]

Return whether the string s contains math expressions.

This is done by checking whether s contains an even number of non-escaped dollar signs.

matplotlib.cbook.is_scalar_or_string(val)[source]

Return whether the given object is a scalar or string like.

matplotlib.cbook.is_writable_file_like(obj)[source]

Return whether obj looks like a file object with a write method.

matplotlib.cbook.local_over_kwdict(local_var, kwargs, *keys)[source]

[Deprecated] Enforces the priority of a local variable over potentially conflicting argument(s) from a kwargs dict. The following possible output values are considered in order of priority:

local_var > kwargs[keys[0]] > ... > kwargs[keys[-1]]

The first of these whose value is not None will be returned. If all are None then None will be returned. Each key in keys will be removed from the kwargs dict in place.

Parameters:
local_varany object

The local variable (highest priority).

kwargsdict

Dictionary of keyword arguments; modified in place.

keysstr(s)

Name(s) of keyword arguments to process, in descending order of priority.

Returns:
any object

Either local_var or one of kwargs[key] for key in keys.

Raises:
IgnoredKeywordWarning

For each key in keys that is removed from kwargs but not used as the output value.

Notes

Deprecated since version 3.3.

class matplotlib.cbook.maxdict(maxsize)[source]

Bases: dict

A dictionary with a maximum size.

Notes

This doesn't override all the relevant methods to constrain the size, just __setitem__, so use with caution.

matplotlib.cbook.normalize_kwargs(kw, alias_mapping=None, required=<deprecated parameter>, forbidden=<deprecated parameter>, allowed=<deprecated parameter>)[source]

Helper function to normalize kwarg inputs.

The order they are resolved are:

  1. aliasing
  2. required
  3. forbidden
  4. allowed

This order means that only the canonical names need appear in allowed, forbidden, required.

Parameters:
kwdict

A dict of keyword arguments.

alias_mappingdict or Artist subclass or Artist instance, optional

A mapping between a canonical name to a list of aliases, in order of precedence from lowest to highest.

If the canonical value is not in the list it is assumed to have the highest priority.

If an Artist subclass or instance is passed, use its properties alias mapping.

requiredlist of str, optional

A list of keys that must be in kws. This parameter is deprecated.

forbiddenlist of str, optional

A list of keys which may not be in kw. This parameter is deprecated.

allowedlist of str, optional

A list of allowed fields. If this not None, then raise if kw contains any keys not in the union of required and allowed. To allow only the required fields pass in an empty tuple allowed=(). This parameter is deprecated.

Raises:
TypeError

To match what python raises if invalid args/kwargs are passed to a callable.

matplotlib.cbook.open_file_cm(path_or_file, mode='r', encoding=None)[source]

Pass through file objects and context-manage path-likes.

matplotlib.cbook.print_cycles(objects, outstream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, show_progress=False)[source]

Print loops of cyclic references in the given objects.

It is often useful to pass in gc.garbage to find the cycles that are preventing some objects from being garbage collected.

Parameters:
objects

A list of objects to find cycles in.

outstream

The stream for output.

show_progressbool

If True, print the number of objects reached as they are found.

matplotlib.cbook.pts_to_midstep(x, *args)[source]

Convert continuous line to mid-steps.

Given a set of N points convert to 2N points which when connected linearly give a step function which changes values at the middle of the intervals.

Parameters:
xarray

The x location of the steps. May be empty.

y1, ..., yparray

y arrays to be turned into steps; all must be the same length as x.

Returns:
array

The x and y values converted to steps in the same order as the input; can be unpacked as x_out, y1_out, ..., yp_out. If the input is length N, each of these arrays will be length 2N.

Examples

>>> x_s, y1_s, y2_s = pts_to_midstep(x, y1, y2)
matplotlib.cbook.pts_to_poststep(x, *args)[source]

Convert continuous line to post-steps.

Given a set of N points convert to 2N + 1 points, which when connected linearly give a step function which changes values at the end of the intervals.

Parameters:
xarray

The x location of the steps. May be empty.

y1, ..., yparray

y arrays to be turned into steps; all must be the same length as x.

Returns:
array

The x and y values converted to steps in the same order as the input; can be unpacked as x_out, y1_out, ..., yp_out. If the input is length N, each of these arrays will be length 2N + 1. For N=0, the length will be 0.

Examples

>>> x_s, y1_s, y2_s = pts_to_poststep(x, y1, y2)
matplotlib.cbook.pts_to_prestep(x, *args)[source]

Convert continuous line to pre-steps.

Given a set of N points, convert to 2N - 1 points, which when connected linearly give a step function which changes values at the beginning of the intervals.

Parameters:
xarray

The x location of the steps. May be empty.

y1, ..., yparray

y arrays to be turned into steps; all must be the same length as x.

Returns:
array

The x and y values converted to steps in the same order as the input; can be unpacked as x_out, y1_out, ..., yp_out. If the input is length N, each of these arrays will be length 2N + 1. For N=0, the length will be 0.

Examples

>>> x_s, y1_s, y2_s = pts_to_prestep(x, y1, y2)
matplotlib.cbook.report_memory(i=0)[source]

Return the memory consumed by the process.

matplotlib.cbook.safe_first_element(obj)[source]

Return the first element in obj.

This is an type-independent way of obtaining the first element, supporting both index access and the iterator protocol.

matplotlib.cbook.safe_masked_invalid(x, copy=False)[source]
matplotlib.cbook.sanitize_sequence(data)[source]

Convert dictview objects to list. Other inputs are returned unchanged.

class matplotlib.cbook.silent_list(type, seq=None)[source]

Bases: list

A list with a short repr().

This is meant to be used for a homogeneous list of artists, so that they don't cause long, meaningless output.

Instead of

[<matplotlib.lines.Line2D object at 0x7f5749fed3c8>,
 <matplotlib.lines.Line2D object at 0x7f5749fed4e0>,
 <matplotlib.lines.Line2D object at 0x7f5758016550>]

one will get

<a list of 3 Line2D objects>
matplotlib.cbook.simple_linear_interpolation(a, steps)[source]

Resample an array with steps - 1 points between original point pairs.

Along each column of a, (steps - 1) points are introduced between each original values; the values are linearly interpolated.

Parameters:
aarray, shape (n, ...)
stepsint
Returns:
array

shape ((n - 1) * steps + 1, ...)

matplotlib.cbook.strip_math(s)[source]

Remove latex formatting from mathtext.

Only handles fully math and fully non-math strings.

matplotlib.cbook.to_filehandle(fname, flag='r', return_opened=False, encoding=None)[source]

Convert a path to an open file handle or pass-through a file-like object.

Consider using open_file_cm instead, as it allows one to properly close newly created file objects more easily.

Parameters:
fnamestr or path-like or file-like

If str or os.PathLike, the file is opened using the flags specified by flag and encoding. If a file-like object, it is passed through.

flagstr, default 'r'

Passed as the mode argument to open when fname is str or os.PathLike; ignored if fname is file-like.

return_openedbool, default False

If True, return both the file object and a boolean indicating whether this was a new file (that the caller needs to close). If False, return only the new file.

encodingstr or None, default None

Passed as the mode argument to open when fname is str or os.PathLike; ignored if fname is file-like.

Returns:
fhfile-like
openedbool

opened is only returned if return_opened is True.

matplotlib.cbook.violin_stats(X, method, points=100, quantiles=None)[source]

Return a list of dictionaries of data which can be used to draw a series of violin plots.

See the Returns section below to view the required keys of the dictionary.

Users can skip this function and pass a user-defined set of dictionaries with the same keys to violinplot instead of using Matplotlib to do the calculations. See the Returns section below for the keys that must be present in the dictionaries.

Parameters:
Xarray-like

Sample data that will be used to produce the gaussian kernel density estimates. Must have 2 or fewer dimensions.

methodcallable

The method used to calculate the kernel density estimate for each column of data. When called via method(v, coords), it should return a vector of the values of the KDE evaluated at the values specified in coords.

pointsint, default: 100

Defines the number of points to evaluate each of the gaussian kernel density estimates at.

quantilesarray-like, default: None

Defines (if not None) a list of floats in interval [0, 1] for each column of data, which represents the quantiles that will be rendered for that column of data. Must have 2 or fewer dimensions. 1D array will be treated as a singleton list containing them.

Returns:
list of dict

A list of dictionaries containing the results for each column of data. The dictionaries contain at least the following:

  • coords: A list of scalars containing the coordinates this particular kernel density estimate was evaluated at.
  • vals: A list of scalars containing the values of the kernel density estimate at each of the coordinates given in coords.
  • mean: The mean value for this column of data.
  • median: The median value for this column of data.
  • min: The minimum value for this column of data.
  • max: The maximum value for this column of data.
  • quantiles: The quantile values for this column of data.
exception matplotlib.cbook.deprecation.MatplotlibDeprecationWarning[source]

Bases: UserWarning

A class for issuing deprecation warnings for Matplotlib users.

In light of the fact that Python builtin DeprecationWarnings are ignored by default as of Python 2.7 (see link below), this class was put in to allow for the signaling of deprecation, but via UserWarnings which are not ignored by default.

https://docs.python.org/dev/whatsnew/2.7.html#the-future-for-python-2-x

matplotlib.cbook.deprecation.deprecated(since, *, message='', name='', alternative='', pending=False, obj_type=None, addendum='', removal='')[source]

Decorator to mark a function, a class, or a property as deprecated.

When deprecating a classmethod, a staticmethod, or a property, the @deprecated decorator should go under @classmethod and @staticmethod (i.e., deprecated should directly decorate the underlying callable), but over @property.

Parameters:
sincestr

The release at which this API became deprecated.

messagestr, optional

Override the default deprecation message. The %(since)s, %(name)s, %(alternative)s, %(obj_type)s, %(addendum)s, and %(removal)s format specifiers will be replaced by the values of the respective arguments passed to this function.

namestr, optional

The name used in the deprecation message; if not provided, the name is automatically determined from the deprecated object.

alternativestr, optional

An alternative API that the user may use in place of the deprecated API. The deprecation warning will tell the user about this alternative if provided.

pendingbool, optional

If True, uses a PendingDeprecationWarning instead of a DeprecationWarning. Cannot be used together with removal.

obj_typestr, optional

The object type being deprecated; by default, 'class' if decorating a class, 'attribute' if decorating a property, 'function' otherwise.

addendumstr, optional

Additional text appended directly to the final message.

removalstr, optional

The expected removal version. With the default (an empty string), a removal version is automatically computed from since. Set to other Falsy values to not schedule a removal date. Cannot be used together with pending.

Examples

Basic example:

@deprecated('1.4.0')
def the_function_to_deprecate():
    pass
matplotlib.cbook.deprecation.mplDeprecation

alias of matplotlib.cbook.deprecation.MatplotlibDeprecationWarning

matplotlib.cbook.deprecation.warn_deprecated(since, *, message='', name='', alternative='', pending=False, obj_type='', addendum='', removal='')[source]

Display a standardized deprecation.

Parameters:
sincestr

The release at which this API became deprecated.

messagestr, optional

Override the default deprecation message. The %(since)s, %(name)s, %(alternative)s, %(obj_type)s, %(addendum)s, and %(removal)s format specifiers will be replaced by the values of the respective arguments passed to this function.

namestr, optional

The name of the deprecated object.

alternativestr, optional

An alternative API that the user may use in place of the deprecated API. The deprecation warning will tell the user about this alternative if provided.

pendingbool, optional

If True, uses a PendingDeprecationWarning instead of a DeprecationWarning. Cannot be used together with removal.

obj_typestr, optional

The object type being deprecated.

addendumstr, optional

Additional text appended directly to the final message.

removalstr, optional

The expected removal version. With the default (an empty string), a removal version is automatically computed from since. Set to other Falsy values to not schedule a removal date. Cannot be used together with pending.

Examples

Basic example:

# To warn of the deprecation of "matplotlib.name_of_module"
warn_deprecated('1.4.0', name='matplotlib.name_of_module',
                obj_type='module')