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.
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: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308
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.
register func to be called when a signal s is generated func will be called
disconnect the callback registered with callback id cid
process signal s. All of the functions registered to receive callbacks on s will be called with *args and **kwargs
Bases: object
Bases: object
This class provides a lightweight way to group arbitrary objects together into disjoint sets when a full-blown 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 weak-referenceable.
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 dead weak references from the dictionary
Returns all of the items joined with a, including itself.
Join given arguments into the same set. Accepts one or more arguments.
Returns True if a and b are members of the same set.
Bases: matplotlib.cbook.Scheduler
Schedule callbacks when scheduler is idle
Bases: exceptions.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.
http://docs.python.org/dev/whatsnew/2.7.html#the-future-for-python-2-x
Bases: object
Bases: object
Null objects always and reliably “do nothing.”
Bases: object
class that implements a not-yet-full buffer
append an element at the end of the buffer
Return a list of elements from the oldest to the newest.
Bases: threading.Thread
Base class for timeout and idle scheduling
Bases: object
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'
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
move the position back and return the current element
raise o to the top of the stack and return o. o must be in the stack
empty the stack
move the position forward and return the current element
push the first element onto the top of the stack
push object onto stack at current position - all elements occurring later than the current position are discarded
remove element o from the stack
Bases: matplotlib.cbook.Scheduler
Schedule recurring events with a wait time in seconds
Bases: dict
All-in-one multiple-string-substitution 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)
Translate text, returns the modified text.
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
Return True if all elements of seq compare equal. If seq is 0 or 1 length, return True
return all possible pairs in sequence x
Condensed by Alex Martelli from this thread on c.l.python
Return True if all elements of seq evaluate to True. If seq is empty, return False.
Returns list of dictionaries of staticists to be use to draw a series of box and whisker plots. See the Returns section below to the required keys of the dictionary. Users can skip this function and pass a user- defined set of dictionaries to the new axes.bxp method instead of relying on MPL to do the calcs.
Parameters: | X : array-like
whis : float, string, or sequence (default = 1.5)
bootstrap : int or None (default)
labels : sequence
|
||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Returns: | bxpstats : list of dict
|
Notes
Non-bootstrapping 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:12-16.
Bases: object
Base class for handling string -> python type with support for missing values
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 non-blank line to determine the indentation.
It is also faster in most cases.
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:
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().
Decorator to mark a function as deprecated.
Parameters: | since : str
message : str, optional
name : str, optional
alternative : str, optional
pending : bool, optional
|
---|
Examples
Basic example:
@deprecated('1.4.0')
def the_function_to_deprecate():
pass
delete all of the keys from the dict d
Returns True if the given writable file-like object requires Unicode to be written to it.
return all attributes of o which match string in match. if case is True require an exact case match.
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: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/121294 and Recipe 1.12 in cookbook
Recurse all the files and dirs in args ignoring symbolic links and return the files as a list of strings
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.
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 ‘mpl-data/sample_data` at the same level of ‘matplotlib` Python module files).
If the filename ends in .gz, the file is implicitly ungzipped.
seq is a list of words. Return the index into seq such that:
len(' '.join(seq[:ind])<=N
.
return true if obj looks like a number
return true if obj is not string like and is not iterable
Return whether the given object is a scalar or string like.
Returns true if obj is iterable and contains strings
Return True if obj looks like a string
return true if obj looks like a file object with a write method
return issubclass(x, klass) and return False on a TypeError
return true if obj is iterable
Recursively list files
from Parmar and Martelli in the Python Cookbook
Bases: dict
A dictionary with a maximum size; this doesn’t override all the relevant methods to contrain size, just setitem, so use with caution
make directory newdir recursively, and set mode. Equivalent to
> mkdir -p NEWDIR
> chmod MODE NEWDIR
alias of MatplotlibDeprecationWarning
Return True if one element of seq is True. It seq is empty, return False.
Break up the seq into num tuples
empty a list
return the memory consumed by process
Return a dictionary that contains those keys that appear in both d and keys, with values from d.
reverse the dictionary – may lose data if values are not unique!
make sure args are equal len before zipping
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
soundex module conforming to Odell-Russell algorithm
remove latex formatting from mathtext
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()
Bases: matplotlib.cbook.converter
convert to a date or None
use a time.strptime() format string for conversion
Bases: matplotlib.cbook.converter
convert to a datetime or None
use a time.strptime() format string for conversion
Bases: matplotlib.cbook.converter
convert to a float or None
Bases: matplotlib.cbook.converter
convert to an int or None
Bases: matplotlib.cbook.converter
convert to string or None
Return a list of unique elements of x
Find index ranges where mask is False.
mask will be flattened if it is not already 1-D.
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.
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 user-defined set of dictionaries to the axes.vplot method instead of using MPL to do the calculations.
Parameters: | X : array-like
method : callable
points : scalar, default = 100
|
---|---|
Returns: | A list of dictionaries containing the results for each column of data. The dictionaries contain at least the following:
|
Used to display deprecation warning in a standard way.
Parameters: | since : str
message : str, optional
name : str, optional
alternative : str, optional
pending : bool, optional
obj_type : str, optional
|
---|
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')
wrap text with prefix at length cols