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.
matplotlib.cbook.
Bunch
(**kwargs)[source]¶Bases: types.SimpleNamespace
Deprecated since version 3.0: The Bunch class was deprecated in Matplotlib 3.0 and will be removed in 3.2. Use types.SimpleNamespace instead.
Often we want to just collect a bunch of stuff together, naming each item of the bunch; a dictionary's OK for that, but a small do nothing class is even handier, and prettier to use. Whenever you want to group a few variables:
>>> point = Bunch(datum=2, squared=4, coord=12)
>>> point.datum
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: 


matplotlib.cbook.
GetRealpathAndStat
(**kwargs)[source]¶Bases: object
Deprecated since version 3.0: The GetRealpathAndStat class was deprecated in Matplotlib 3.0 and will be removed in 3.2.
matplotlib.cbook.
Grouper
(init=())[source]¶Bases: object
This class provides a lightweight way to group arbitrary objects together into disjoint sets when a fullblown graph data structure would be overkill.
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 weakreferenceable.
For example:
>>> from matplotlib.cbook import Grouper
>>> class Foo(object):
... 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
matplotlib.cbook.
IgnoredKeywordWarning
[source]¶Bases: UserWarning
A class for issuing warnings about keyword arguments that will be ignored by matplotlib
matplotlib.cbook.
Locked
(**kwargs)[source]¶Bases: object
Deprecated since version 3.0: The Locked class was deprecated in Matplotlib 3.0 and will be removed in 3.2.
Context manager to handle locks.
Based on code from conda.
(c) 20122013 Continuum Analytics, Inc. / https://www.continuum.io/ All Rights Reserved
conda is distributed under the terms of the BSD 3clause license. Consult LICENSE_CONDA or https://opensource.org/licenses/BSD3Clause.
LOCKFN
= '.matplotlib_lock'¶TimeoutError
[source]¶Bases: RuntimeError
matplotlib.cbook.
Stack
(default=None)[source]¶Bases: object
Stack of elements with a movable cursor.
Mimics home/back/forward in a web browser.
matplotlib.cbook.
align_iterators
(func, *iterables)[source]¶Deprecated since version 2.2: The align_iterators function was deprecated in Matplotlib 2.2 and will be removed in 3.1.
This generator takes a bunch of iterables that are ordered by func It sends out ordered tuples:
(func(row), [rows from all iterators matching func(row)])
It is used by matplotlib.mlab.recs_join()
to join record arrays
matplotlib.cbook.
boxplot_stats
(X, whis=1.5, bootstrap=None, labels=None, autorange=False)[source]¶Returns list of dictionaries of statistics used to draw a series
of box and whisker plots. The Returns
section enumerates the
required keys of the dictionary. Users can skip this function and
pass a userdefined set of dictionaries to the new axes.bxp
method
instead of relying on MPL to do the calculations.
Parameters: 



Returns: 

Notes
Nonbootstrapping approach to confidence interval uses Gaussian based asymptotic approximation:
General approach from: McGill, R., Tukey, J.W., and Larsen, W.A. (1978) "Variations of Boxplots", The American Statistician, 32:1216.
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.
dedent
(s)[source]¶Remove excess indentation from docstring s.
Discards any leading blank lines, then removes up to n whitespace characters from each line, where n is the number of leading whitespace characters in the first line. It differs from textwrap.dedent in its deletion of leading blank lines and its use of the first nonblank line to determine the indentation.
It is also faster in most cases.
matplotlib.cbook.
delete_masked_points
(*args)[source]¶Find all masked and/or nonfinite points in a set of arguments, and return the arguments with only the unmasked points remaining.
Arguments can be in any of 5 categories:
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 np.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]¶Returns True
if the given writable filelike object requires Unicode
to be written to it.
matplotlib.cbook.
flatten
(seq, scalarp=<function is_scalar_or_string>)[source]¶Returns 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_sample_data
(fname, asfileobj=True)[source]¶Return a sample data file. fname is a path relative to the
mpldata/sample_data
directory. If asfileobj is True
return a file object, otherwise just a file path.
Set the rc parameter examples.directory to the directory where we should look, if sample_data files are stored in a location different than default (which is 'mpldata/sample_data` at the same level of 'matplotlib` Python module files).
If the filename ends in .gz, the file is implicitly ungzipped.
matplotlib.cbook.
index_of
(y)[source]¶A helper function to get the index of an input to plot against if x values are not explicitly given.
Tries to get y.index
(works if this is a pd.Series), if that
fails, return np.arange(y.shape[0]).
This will be extended in the future to deal with more types of labeled data.
Parameters: 


Returns: 

matplotlib.cbook.
is_numlike
(obj)[source]¶Deprecated since version 3.0: isinstance(..., numbers.Number)
return true if obj looks like a number
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 true if obj looks like a file object with a write method
matplotlib.cbook.
listFiles
(root, patterns='*', recurse=1, return_folders=0)[source]¶Deprecated since version 3.0: The listFiles function was deprecated in Matplotlib 3.0 and will be removed in 3.2.
Recursively list files
from Parmar and Martelli in the Python Cookbook
matplotlib.cbook.
local_over_kwdict
(local_var, kwargs, *keys)[source]¶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: 


Returns: 

Raises: 

matplotlib.cbook.
maxdict
(maxsize)[source]¶Bases: dict
A dictionary with a maximum size; this doesn't override all the relevant methods to constrain the size, just setitem, so use with caution
matplotlib.cbook.
mkdirs
(newdir, mode=511)[source]¶Deprecated since version 3.0: The mkdirs function was deprecated in Matplotlib 3.0 and will be removed in 3.2.
make directory newdir recursively, and set mode. Equivalent to
> mkdir p NEWDIR
> chmod MODE NEWDIR
matplotlib.cbook.
normalize_kwargs
(kw, alias_mapping=None, required=(), forbidden=(), allowed=None)[source]¶Helper function to normalize kwarg inputs
The order they are resolved are:
 aliasing
 required
 forbidden
 allowed
This order means that only the canonical names need appear in
allowed
, forbidden
, required
Parameters: 


Raises: 

matplotlib.cbook.
open_file_cm
(path_or_file, mode='r', encoding=None)[source]¶Pass through file objects and contextmanage PathLike
s.
matplotlib.cbook.
print_cycles
(objects, outstream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF8'>, show_progress=False)[source]¶matplotlib.cbook.
pts_to_midstep
(x, *args)[source]¶Convert continuous line to midsteps.
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: 


Returns: 

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 poststeps.
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: 


Returns: 

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 presteps.
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: 


Returns: 

Examples
>> x_s, y1_s, y2_s = pts_to_prestep(x, y1, y2)
matplotlib.cbook.
silent_list
(type, seq=None)[source]¶Bases: list
override repr when returning a list of matplotlib artists to prevent long, meaningless output. This is meant to be used for a homogeneous list of a given type
matplotlib.cbook.
simple_linear_interpolation
(a, steps)[source]¶Resample an array with steps  1
points between original point pairs.
Parameters: 


Returns: 

matplotlib.cbook.
to_filehandle
(fname, flag='rU', return_opened=False, encoding=None)[source]¶fname can be an os.PathLike
or a file handle. Support for gzipped
files is automatic, if the filename ends in .gz. flag is a
read/write flag for file()
matplotlib.cbook.
unicode_safe
(s)[source]¶Deprecated since version 3.0: The unicode_safe function was deprecated in Matplotlib 3.0 and will be removed in 3.2.
matplotlib.cbook.
violin_stats
(X, method, points=100)[source]¶Returns 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 userdefined set
of dictionaries to the axes.vplot
method instead of using MPL to do the
calculations.
Parameters: 


Returns: 
