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.Bunch(**kwds)
Bases: object
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 By: Alex Martelli From: https://code.activestate.com/recipes/121294/
class matplotlib.cbook.CallbackRegistry(exception_handler=<function _exception_printer>)
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. The Python stdlib weakref module can not create weak references to bound methods directly, so we need to create a proxy object to handle weak references to bound methods (or regular free functions). This technique was shared by Peter Parente on his “Mindtrove” blog.
Parameters: 
exception_handler : callable, optional If provided must have signature def handler(exc: Exception) > None: If not None this function will be called with any The callable must be pickleable. The default handler is def h(exc): traceback.print_exc() 

connect(s, func)
register func to be called when a signal s is generated func will be called
disconnect(cid)
disconnect the callback registered with callback id cid
process(s, *args, **kwargs)
process signal s
. All of the functions registered to receive callbacks on s
will be called with **args
and **kwargs
class matplotlib.cbook.GetRealpathAndStat
Bases: object
class matplotlib.cbook.Grouper(init=())
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 retreived 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
clean()
Clean dead weak references from the dictionary
get_siblings(a)
Returns all of the items joined with a, including itself.
join(a, *args)
Join given arguments into the same set. Accepts one or more arguments.
joined(a, b)
Returns True if a and b are members of the same set.
remove(a)
exception matplotlib.cbook.IgnoredKeywordWarning
Bases: UserWarning
A class for issuing warnings about keyword arguments that will be ignored by matplotlib
class matplotlib.cbook.Locked(path)
Bases: object
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'
exception TimeoutError
Bases: RuntimeError
class matplotlib.cbook.Null(*args, **kwargs)
Bases: object
Deprecated since version 2.1: The Null class was deprecated in version 2.1.
Null objects always and reliably “do nothing.”
class matplotlib.cbook.RingBuffer(*args, **kwargs)
Bases: object
Deprecated since version 2.1: The RingBuffer class was deprecated in version 2.1.
class that implements a notyetfull buffer
append(x)
append an element at the end of the buffer
get()
Return a list of elements from the oldest to the newest.
class matplotlib.cbook.Sorter(*args, **kwargs)
Bases: object
Deprecated since version 2.1: sorted(…, key=itemgetter(…))
Sort by attribute or item
Example usage:
sort = Sorter() list = [(1, 2), (4, 8), (0, 3)] dict = [{'a': 3, 'b': 4}, {'a': 5, 'b': 2}, {'a': 0, 'b': 0}, {'a': 9, 'b': 9}] sort(list) # default sort sort(list, 1) # sort by index 1 sort(dict, 'a') # sort a list of dicts by key 'a'
byAttribute(data, attributename, inplace=1)
byItem(data, itemindex=None, inplace=1)
sort(data, itemindex=None, inplace=1)
class matplotlib.cbook.Stack(default=None)
Bases: object
Implement a stack where elements can be pushed on and you can move back and forth. But no pop. Should mimic home / back / forward in a browser
back()
move the position back and return the current element
bubble(o)
raise o to the top of the stack and return o. o must be in the stack
clear()
empty the stack
empty()
forward()
move the position forward and return the current element
home()
push the first element onto the top of the stack
push(o)
push object onto stack at current position  all elements occurring later than the current position are discarded
remove(o)
remove element o from the stack
class matplotlib.cbook.Xlator(*args, **kwargs)
Bases: dict
Deprecated since version 2.1: The Xlator class was deprecated in version 2.1.
Allinone multiplestringsubstitution class
Example usage:
text = "Larry Wall is the creator of Perl" adict = { "Larry Wall" : "Guido van Rossum", "creator" : "Benevolent Dictator for Life", "Perl" : "Python", } print(multiple_replace(adict, text)) xlat = Xlator(adict) print(xlat.xlat(text))
xlat(text)
Translate text, returns the modified text.
matplotlib.cbook.align_iterators(func, *iterables)
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.allequal(seq)
Deprecated since version 2.1: The allequal function was deprecated in version 2.1.
Return True if all elements of seq compare equal. If seq is 0 or 1 length, return True
matplotlib.cbook.allpairs(x)
Deprecated since version 2.1: The allpairs function was deprecated in version 2.1.
return all possible pairs in sequence x
matplotlib.cbook.alltrue(seq)
Deprecated since version 2.1: The alltrue function was deprecated in version 2.1.
Return True if all elements of seq evaluate to True. If seq is empty, return False.
matplotlib.cbook.boxplot_stats(X, whis=1.5, bootstrap=None, labels=None, autorange=False)
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: 
X : arraylike Data that will be represented in the boxplots. Should have 2 or fewer dimensions. whis : float, string, or sequence (default = 1.5) As a float, determines the reach of the whiskers to the beyond the first and third quartiles. In other words, where IQR is the interquartile range ( bootstrap : int, optional Number of times the confidence intervals around the median should be bootstrapped (percentile method). labels : arraylike, optional Labels for each dataset. Length must be compatible with dimensions of autorange : bool, optional (False) When  

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

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.
class matplotlib.cbook.converter(*args, **kwargs)
Bases: object
Deprecated since version 2.1: The converter class was deprecated in version 2.1.
Base class for handling string > python type with support for missing values
is_missing(s)
matplotlib.cbook.dedent(s)
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)
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.dict_delall(d, keys)
Deprecated since version 2.1: The dict_delall function was deprecated in version 2.1.
delete all of the keys from the dict
d
matplotlib.cbook.exception_to_str(s=None)
Deprecated since version 2.1: The exception_to_str function was deprecated in version 2.1.
matplotlib.cbook.file_requires_unicode(x)
Returns True
if the given writable filelike object requires Unicode to be written to it.
matplotlib.cbook.finddir(o, match, case=False)
Deprecated since version 2.1: The finddir function was deprecated in version 2.1.
return all attributes of o which match string in match. if case is True require an exact case match.
matplotlib.cbook.flatten(seq, scalarp=<function is_scalar_or_string>)
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_label(y, default_name)
matplotlib.cbook.get_recursive_filelist(args)
Deprecated since version 2.1: The get_recursive_filelist function was deprecated in version 2.1.
Recurse all the files and dirs in args ignoring symbolic links and return the files as a list of strings
matplotlib.cbook.get_sample_data(fname, asfileobj=True)
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.get_split_ind(seq, N)
Deprecated since version 2.1: The get_split_ind function was deprecated in version 2.1.
seq is a list of words. Return the index into seq such that:
len(' '.join(seq[:ind])<=N
.
matplotlib.cbook.index_of(y)
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: 
y : scalar or arraylike The proposed yvalue 

Returns: 
x, y : ndarray The x and y values to plot. 
matplotlib.cbook.is_hashable(obj)
Returns true if obj can be hashed
matplotlib.cbook.is_math_text(s)
matplotlib.cbook.is_numlike(obj)
return true if obj looks like a number
matplotlib.cbook.is_scalar(obj)
Deprecated since version 2.1: The is_scalar function was deprecated in version 2.1.
return true if obj is not string like and is not iterable
matplotlib.cbook.is_scalar_or_string(val)
Return whether the given object is a scalar or string like.
matplotlib.cbook.is_sequence_of_strings(obj)
Deprecated since version 2.1: The is_sequence_of_strings function was deprecated in version 2.1.
Returns true if obj is iterable and contains strings
matplotlib.cbook.is_string_like(obj)
Deprecated since version 2.1: The is_string_like function was deprecated in version 2.1.
Return True if obj looks like a string
matplotlib.cbook.is_writable_file_like(obj)
return true if obj looks like a file object with a write method
matplotlib.cbook.issubclass_safe(x, klass)
Deprecated since version 2.1: The issubclass_safe function was deprecated in version 2.1.
return issubclass(x, klass) and return False on a TypeError
matplotlib.cbook.iterable(obj)
return true if obj is iterable
matplotlib.cbook.listFiles(root, patterns='*', recurse=1, return_folders=0)
Recursively list files
from Parmar and Martelli in the Python Cookbook
matplotlib.cbook.local_over_kwdict(local_var, kwargs, *keys)
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_var: any object The local variable (highest priority)


Returns: 
out: 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 
class matplotlib.cbook.maxdict(maxsize)
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)
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)
Helper function to normalize kwarg inputs
The order they are resolved are:
This order means that only the canonical names need appear in allowed
, forbidden
, required
Parameters: 
alias_mapping, dict, 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. required : iterable, optional A tuple of fields that must be in kwargs. forbidden : iterable, optional A list of keys which may not be in kwargs allowed : tuple, optional A tuple of allowed fields. If this not None, then raise if 

Raises: 
TypeError To match what python raises if invalid args/kwargs are passed to a callable. 
matplotlib.cbook.onetrue(seq)
Deprecated since version 2.1: The onetrue function was deprecated in version 2.1.
Return True if one element of seq is True. It seq is empty, return False.
matplotlib.cbook.pieces(seq, num=2)
Deprecated since version 2.1: The pieces function was deprecated in version 2.1.
Break up the seq into num tuples
matplotlib.cbook.print_cycles(objects, outstream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF8'>, show_progress=False)
matplotlib.cbook.pts_to_midstep(x, *args)
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: 
x : array The x location of the steps. y1, …, yp : array y arrays to be turned into steps; all must be the same length as 

Returns: 
out : array The x and y values converted to steps in the same order as the input; can be unpacked as 
>> x_s, y1_s, y2_s = pts_to_midstep(x, y1, y2)
matplotlib.cbook.pts_to_poststep(x, *args)
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: 
x : array The x location of the steps. y1, …, yp : array y arrays to be turned into steps; all must be the same length as 

Returns: 
out : array The x and y values converted to steps in the same order as the input; can be unpacked as 
>> x_s, y1_s, y2_s = pts_to_poststep(x, y1, y2)
matplotlib.cbook.pts_to_prestep(x, *args)
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: 
x : array The x location of the steps. y1, …, yp : array y arrays to be turned into steps; all must be the same length as 

Returns: 
out : array The x and y values converted to steps in the same order as the input; can be unpacked as 
>> x_s, y1_s, y2_s = pts_to_prestep(x, y1, y2)
matplotlib.cbook.recursive_remove(path)
Deprecated since version 2.1: The recursive_remove function was deprecated in version 2.1. Use shutil.rmtree instead.
matplotlib.cbook.report_memory(i=0)
return the memory consumed by process
matplotlib.cbook.restrict_dict(d, keys)
Deprecated since version 2.1: The restrict_dict function was deprecated in version 2.1.
Return a dictionary that contains those keys that appear in both d and keys, with values from d.
matplotlib.cbook.reverse_dict(d)
Deprecated since version 2.1: The reverse_dict function was deprecated in version 2.1.
reverse the dictionary – may lose data if values are not unique!
matplotlib.cbook.safe_first_element(obj)
matplotlib.cbook.safe_masked_invalid(x, copy=False)
matplotlib.cbook.safezip(*args)
make sure args are equal len before zipping
matplotlib.cbook.sanitize_sequence(data)
Converts dictview object to list
class matplotlib.cbook.silent_list(type, seq=None)
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)
matplotlib.cbook.soundex(name, len=4)
Deprecated since version 2.1: The soundex function was deprecated in version 2.1.
soundex module conforming to OdellRussell algorithm
matplotlib.cbook.strip_math(s)
remove latex formatting from mathtext
matplotlib.cbook.to_filehandle(fname, flag='rU', return_opened=False)
fname can be a filename or a file handle. Support for gzipped files is automatic, if the filename ends in .gz. flag is a read/write flag for file()
class matplotlib.cbook.todate(*args, **kwargs)
Bases: matplotlib.cbook.converter
Deprecated since version 2.1: The todate class was deprecated in version 2.1.
convert to a date or None
class matplotlib.cbook.todatetime(*args, **kwargs)
Bases: matplotlib.cbook.converter
Deprecated since version 2.1: The todatetime class was deprecated in version 2.1.
convert to a datetime or None
class matplotlib.cbook.tofloat(*args, **kwargs)
Bases: matplotlib.cbook.converter
Deprecated since version 2.1: The tofloat class was deprecated in version 2.1.
convert to a float or None
class matplotlib.cbook.toint(*args, **kwargs)
Bases: matplotlib.cbook.converter
Deprecated since version 2.1: The toint class was deprecated in version 2.1.
convert to an int or None
class matplotlib.cbook.tostr(*args, **kwargs)
Bases: matplotlib.cbook.converter
Deprecated since version 2.1: The tostr class was deprecated in version 2.1.
convert to string or None
matplotlib.cbook.unicode_safe(s)
matplotlib.cbook.unique(x)
Deprecated since version 2.1: The unique function was deprecated in version 2.1.
Return a list of unique elements of x
matplotlib.cbook.unmasked_index_ranges(mask, compressed=True)
Deprecated since version 2.1: The unmasked_index_ranges function was deprecated in version 2.1.
Find index ranges where mask is False.
mask will be flattened if it is not already 1D.
Returns Nx2 numpy.ndarray
with each row the start and stop indices for slices of the compressed numpy.ndarray
corresponding to each of N uninterrupted runs of unmasked values. If optional argument compressed is False, it returns the start and stop indices into the original numpy.ndarray
, not the compressed numpy.ndarray
. Returns None if there are no unmasked values.
Example:
y = ma.array(np.arange(5), mask = [0,0,1,0,0]) ii = unmasked_index_ranges(ma.getmaskarray(y)) # returns array [[0,2,] [2,4,]] y.compressed()[ii[1,0]:ii[1,1]] # returns array [3,4,] ii = unmasked_index_ranges(ma.getmaskarray(y), compressed=False) # returns array [[0, 2], [3, 5]] y.filled()[ii[1,0]:ii[1,1]] # returns array [3,4,]
Prior to the transforms refactoring, this was used to support masked arrays in Line2D.
matplotlib.cbook.violin_stats(X, method, points=100)
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: 
X : arraylike Sample data that will be used to produce the gaussian kernel density estimates. Must have 2 or fewer dimensions. method : callable The method used to calculate the kernel density estimate for each column of data. When called via points : scalar, default = 100 Defines the number of points to evaluate each of the gaussian kernel density estimates at. 

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

matplotlib.cbook.wrap(prefix, text, cols)
Deprecated since version 2.1: The wrap function was deprecated in version 2.1. Use textwrap.TextWrapper instead.
wrap text with prefix at length cols
© 2012–2017 Matplotlib Development Team. All rights reserved.
Licensed under the Matplotlib License Agreement.
http://matplotlib.org/2.1.0/api/cbook_api.html