matplotlib.cbook
#
A collection of utility functions and classes. Originally, many(but not all) were from the Python Cookbook -- hence the name cbook.
- classmatplotlib.cbook.CallbackRegistry(exception_handler=<function_exception_printer>,*,signals=None)[source]#
Bases:
object
Handle registering, processing, blocking, and disconnectingfor a set of signals and callbacks:
>>>defoneat(x):...print('eat',x)>>>defondrink(x):...print('drink',x)
>>>frommatplotlib.cbookimportCallbackRegistry>>>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
>>>withcallbacks.blocked(signal='drink'):...callbacks.process('drink',123)# nothing will be called>>>callbacks.process('drink',123)drink 123
In practice, one should always disconnect all callbacks when they areno 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 referencesto bound methods only, so when the destination object needs to die, theCallbackRegistry won't keep it alive.
- Parameters:
- exception_handlercallable, optional
If not None,exception_handler must be a function that takes an
Exception
as single parameter. It gets called with anyException
raised by the callbacks duringCallbackRegistry.process
, and mayeither re-raise the exception or handle it in another manner.The default handler prints the exception (with
traceback.print_exc
) ifan interactive event loop is running; it re-raises the exception if nointeractive event loop is running.- signalslist, optional
If not None,signals is a list of signals that this registry handles:attempting to
process
or toconnect
to a signal not in the listthrows aValueError
. The default, None, does not restrict thehandled signals.
- blocked(*,signal=None)[source]#
Block callback signals from being processed.
A context manager to temporarily block/disable callback signalsfrom being processed by the registered listeners.
- Parameters:
- signalstr, optional
The callback signal to block. The default is to block all signals.
- classmatplotlib.cbook.Grouper(init=())[source]#
Bases:
object
A disjoint-set data structure.
Objects can be joined using
join()
, tested for connectednessusingjoined()
, and all disjoint sets can be retrieved byusing the object as an iterator.The objects being joined must be hashable and weak-referenceable.
Examples
>>>frommatplotlib.cbookimportGrouper>>>classFoo:...def__init__(self,s):...self.s=s...def__repr__(self):...returnself.s...>>>a,b,c,d,e,f=[Foo(x)forxin'abcdef']>>>grp=Grouper()>>>grp.join(a,b)>>>grp.join(b,c)>>>grp.join(d,e)>>>list(grp)[[a, b, c], [d, e]]>>>grp.joined(a,b)True>>>grp.joined(a,c)True>>>grp.joined(a,d)False
- 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 boxand whisker plots using
bxp
.- Parameters:
- Xarray-like
Data that will be represented in the boxplots. Should have 2 orfewer 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 belowQ3+whis*(Q3-Q1)
, where Q1 and Q3 are the first and thirdquartiles. The default value ofwhis=1.5
corresponds to Tukey'soriginal definition of boxplots.If a pair of floats, they indicate the percentiles at which to draw thewhiskers (e.g., (5, 95)). In particular, setting this to (0, 100)results in whiskers covering the whole range of the data.
In the edge case where
Q1==Q3
,whis is automatically set to(0, 100) (cover the whole range of the data) ifautorange is True.Beyond the whiskers, data are considered outliers and are plotted asindividual points.
- bootstrapint, optional
Number of times the confidence intervals around the medianshould be bootstrapped (percentile method).
- labelslist of str, optional
Labels for each dataset. Length must be compatible withdimensions ofX.
- autorangebool, optional (False)
When
True
and the data are distributed such that the 25th and 75thpercentiles are equal,whis
is set to (0, 100) such that thewhisker ends are at the minimum and maximum of the data.
- Returns:
- list of dict
A list of dictionaries containing the results for each columnof 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)
iqr
interquartile range
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-basedasymptotic 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 ofBoxplots", The American Statistician, 32:12-16.
- matplotlib.cbook.contiguous_regions(mask)[source]#
Return a list of (ind0, ind1) such that
mask[ind0:ind1].all()
isTrue 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-D masked arrays
1-D ndarrays
ndarrays with more than one dimension
other non-string iterables
anything else
The first argument must be in one of the first four categories;any argument with a length differing from that of the firstargument (and hence anything in category 5) then will bepassed through unchanged.
Masks are obtained from all arguments of the correct lengthin categories 1, 2, and 4; a point is bad if masked in a maskedarray or if it is a nan or inf. No attempt is made toextract 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 returnedas ndarrays after removing the points or rows corresponding tomasks in any of the arguments.
A vastly simpler version of this function was originallywritten as a helper for Axes.scatter().
- matplotlib.cbook.file_requires_unicode(x)[source]#
Return whether the given writable file-like object requires Unicode to bewritten to it.
- matplotlib.cbook.flatten(seq,scalarp=<functionis_scalar_or_string>)[source]#
Return a generator of flattened nested containers.
For example:
>>>frommatplotlib.cbookimportflatten>>>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 BlissettFrom:https://code.activestate.com/recipes/121294-simple-generator-for-flattening-nested-containers/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
mpl-data/sample_data
directory. Ifasfileobj isTrue
return a file object, otherwise just a file path.Sample data files are stored in the 'mpl-data/sample_data' directory withinthe Matplotlib package.
If the filename ends in .gz, the file is implicitly ungzipped. If thefilename ends with .npy or .npz, andasfileobj is
True
, the file isloaded withnumpy.load
.
- matplotlib.cbook.index_of(y)[source]#
A helper function to create reasonable x values for the giveny.
This is used for plotting (x, y) if x values are not explicitly given.
First try
y.index
(assumingy is apandas.Series
), if thatfails, userange(len(y))
.This will be extended in the future to deal with more types oflabeled 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 strings contains math expressions.
This is done by checking whethers contains an even number ofnon-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 whetherobj looks like a file object with awrite method.
- matplotlib.cbook.ls_mapper={'-':'solid','--':'dashed','-.':'dashdot',':':'dotted'}#
Maps short codes for line style to their full name used by backends.
- matplotlib.cbook.ls_mapper_r={'dashdot':'-.','dashed':'--','dotted':':','solid':'-'}#
Maps full names for line styles used by backends to their short codes.
- matplotlib.cbook.normalize_kwargs(kw,alias_mapping=None)[source]#
Helper function to normalize kwarg inputs.
- Parameters:
- kwdict or None
A dict of keyword arguments. None is explicitly supported and treatedas an empty dict, to support functions with an optional parameter ofthe form
props=None
.- alias_mappingdict or Artist subclass or Artist instance, optional
A mapping between a canonical name to a list of aliases, in order ofprecedence from lowest to highest.
If the canonical value is not in the list it is assumed to have thehighest priority.
If an Artist subclass or instance is passed, use its properties aliasmapping.
- Raises:
- TypeError
To match what Python raises if invalid arguments/keyword arguments arepassed 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.TextIOWrappername='<stdout>'mode='w'encoding='utf-8'>,show_progress=False)[source]#
Print loops of cyclic references in the givenobjects.
It is often useful to pass in
gc.garbage
to find the cycles that arepreventing 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 to2N
points which when connectedlinearly give a step function which changes values at the middle of theintervals.- 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 islengthN
, each of these arrays will be length2N
.
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 to2N+1
points, which whenconnected linearly give a step function which changes values at the end ofthe 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 islengthN
, each of these arrays will be length2N+1
. ForN=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 to2N-1
points, which whenconnected linearly give a step function which changes values at thebeginning 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 islengthN
, each of these arrays will be length2N+1
. ForN=0
, the length will be 0.
Examples
>>>x_s,y1_s,y2_s=pts_to_prestep(x,y1,y2)
- matplotlib.cbook.safe_first_element(obj)[source]#
Return the first element inobj.
This is a type-independent way of obtaining the first element,supporting both index access and the iterator protocol.
- matplotlib.cbook.sanitize_sequence(data)[source]#
Convert dictview objects to list. Other inputs are returned unchanged.
- classmatplotlib.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 theydon't cause long, meaningless output.
Instead of
[<matplotlib.lines.Line2Dobjectat0x7f5749fed3c8>,<matplotlib.lines.Line2Dobjectat0x7f5749fed4e0>,<matplotlib.lines.Line2Dobjectat0x7f5758016550>]
one will get
<alistof3Line2Dobjects>
If
self.type
is None, the type name is obtained from the first item inthe list (if any).
- matplotlib.cbook.simple_linear_interpolation(a,steps)[source]#
Resample an array with
steps-1
points between original point pairs.Along each column ofa,
(steps-1)
points are introduced betweeneach 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 closenewly created file objects more easily.- Parameters:
- fnamestr or path-like or file-like
If
str
oros.PathLike
, the file is opened using the flags specifiedbyflag andencoding. If a file-like object, it is passed through.- flagstr, default: 'r'
Passed as themode argument to
open
whenfname isstr
oros.PathLike
; ignored iffname is file-like.- return_openedbool, default: False
If True, return both the file object and a boolean indicating whetherthis was a new file (that the caller needs to close). If False, returnonly the new file.
- encodingstr or None, default: None
Passed as themode argument to
open
whenfname isstr
oros.PathLike
; ignored iffname is file-like.
- Returns:
- fhfile-like
- openedbool
opened is only returned ifreturn_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 seriesof violin plots.
See the
Returns
section below to view the required keys of thedictionary.Users can skip this function and pass a user-defined set of dictionarieswith the same keys to
violinplot
instead of using Matplotlibto do the calculations. See theReturns section below for the keysthat must be present in the dictionaries.- Parameters:
- Xarray-like
Sample data that will be used to produce the gaussian kernel densityestimates. Must have 2 or fewer dimensions.
- methodcallable
The method used to calculate the kernel density estimate for eachcolumn of data. When called via
method(v,coords)
, it shouldreturn a vector of the values of the KDE evaluated at the valuesspecified in coords.- pointsint, default: 100
Defines the number of points to evaluate each of the gaussian kerneldensity estimates at.
- quantilesarray-like, default: None
Defines (if not None) a list of floats in interval [0, 1] for eachcolumn of data, which represents the quantiles that will be renderedfor that column of data. Must have 2 or fewer dimensions. 1D array willbe 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 particularkernel density estimate was evaluated at.
vals: A list of scalars containing the values of the kernel densityestimate at each of the coordinates given incoords.
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.