Table Of Contents

Previous topic

matplotlib axis

Next topic

matplotlib cm

This Page

matplotlib cbook


A collection of utility functions and classes. Many (but not all) from the Python Cookbook – hence the name cbook

class matplotlib.cbook.Bunch(**kwds)

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:

class matplotlib.cbook.CallbackRegistry(signals)

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

signals = 'eat', 'drink', 'be merry'

def oneat(x):
    print 'eat', x

def ondrink(x):
    print 'drink', x

callbacks = CallbackRegistry(signals)

ideat = callbacks.connect('eat', oneat)
iddrink = callbacks.connect('drink', ondrink)

#tmp = callbacks.connect('drunk', ondrink) # this will raise a ValueError

callbacks.process('drink', 123)    # will call oneat
callbacks.process('eat', 456)      # will call ondrink
callbacks.process('be merry', 456) # nothing will be called
callbacks.disconnect(ideat)        # disconnect oneat
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.

signals is a sequence of valid signals

class BoundMethodProxy(cb)

Bases: object

Our own proxy object which enables weak references to bound and unbound methods and arbitrary callables. Pulls information about the function, class, and instance out of a bound method. Stores a weak reference to the instance to support garbage collection.

@organization: IBM Corporation @copyright: Copyright (c) 2005, 2006 IBM Corporation @license: The BSD License

Minor bugfixes by Michael Droettboom

CallbackRegistry.connect(s, func)

register func to be called when a signal s is generated func will be called


disconnect the callback registered with callback id cid

CallbackRegistry.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
class matplotlib.cbook.Grouper(init=[])

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:

>>> 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']
>>> g = Grouper()
>>> g.join(a, b)
>>> g.join(b, c)
>>> g.join(d, e)
>>> list(g)
[[d, e], [a, b, c]]
>>> g.joined(a, b)
>>> g.joined(a, c)
>>> g.joined(a, d)

Clean dead weak references from the dictionary


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.

class matplotlib.cbook.Idle(func)

Bases: matplotlib.cbook.Scheduler

Schedule callbacks when scheduler is idle

class matplotlib.cbook.MemoryMonitor(nmax=20000)
plot(i0=0, isub=1, fig=None)
xy(i0=0, isub=1)
class matplotlib.cbook.Null(*args, **kwargs)

Null objects always and reliably “do nothing.”

class matplotlib.cbook.RingBuffer(size_max)

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.

class matplotlib.cbook.Scheduler

Bases: threading.Thread

Base class for timeout and idle scheduling

class matplotlib.cbook.Sorter

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


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

class matplotlib.cbook.Timeout(wait, func)

Bases: matplotlib.cbook.Scheduler

Schedule recurring events with a wait time in seconds

class matplotlib.cbook.ViewVCCachedServer(cache_dir, baseurl)

Bases: urllib2.BaseHandler

Urllib2 handler that takes care of caching files. The file cache.pck holds the directory of files that have been cached.

cache_file(url, data, headers)

Store a received file in the cache directory.

get_sample_data(fname, asfileobj=True)

Check the cachedirectory for a sample_data file. If it does not exist, fetch it with urllib from the svn repo and store it in the cachedir.

If asfileobj is True, a file object will be returned. Else the path to the file as a string will be returned.

http_error_304(req, fp, code, msg, hdrs)

Read the file from the cache since the server has no newer version.


Make the request conditional if we have a cached file.

http_response(req, response)

Update the cache with the returned file.


Read the cache file from the cache directory.


Remove files from the cache directory that are not listed in cache.pck.


Write the cache data structure into the cache directory.

class matplotlib.cbook.Xlator

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.

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


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.

class matplotlib.cbook.converter(missing='Null', missingval=None)

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:

  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 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)

delete all of the keys from the dict d


This function has been moved to matplotlib.mlab – please import it from there

matplotlib.cbook.finddir(o, match, case=False)

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 at 0x2f19410>)

this generator flattens nested containers such as

>>> l=( ('John', 'Hunter'), (1,23), [[[[42,(5,23)]]]])

so that

>>> for i in flatten(l): print i,
John Hunter 1 23 42 5 23

By: Composite of Holger Krekel and Luther Blissett From: 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

matplotlib.cbook.get_sample_data(fname, asfileobj=True)

Check the cachedirectory ~/.matplotlib/sample_data for a sample_data file. If it does not exist, fetch it with urllib from the mpl svn repo

and store it in the cachedir.

If asfileobj is True, a file object will be returned. Else the path to the file as a string will be returned

To add a datafile to this directory, you need to check out sample_data from matplotlib svn:

svn co

and svn add the data file you want to support. This is primarily intended for use in mpl examples that need custom data.

To bypass all downloading, set the rc parameter to False and to the directory where we should look.

matplotlib.cbook.get_split_ind(seq, N)

seq is a list of words. Return the index into seq such that:

len(' '.join(seq[:ind])<=N

This function has been moved to matplotlib.mlab – please import it from there


return true if obj looks like a number


return true if obj is not string like and is not iterable


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

matplotlib.cbook.issubclass_safe(x, klass)

return issubclass(x, klass) and return False on a TypeError


This function has been moved to matplotlib.mlab – please import it from there


return true if obj is iterable

matplotlib.cbook.less_simple_linear_interpolation(x, y, xi, extrap=False)

This function has been moved to matplotlib.mlab – please import it from there

matplotlib.cbook.listFiles(root, patterns='*', recurse=1, return_folders=0)

Recursively list files

from Parmar and Martelli in the Python Cookbook

class matplotlib.cbook.maxdict(maxsize)

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

matplotlib.cbook.mkdirs(newdir, mode=511)

make directory newdir recursively, and set mode. Equivalent to

> mkdir -p NEWDIR

Return True if one element of seq is True. It seq is empty, return False.


This function has been moved to matplotlib.mlab – please import it from there

matplotlib.cbook.pieces(seq, num=2)

Break up the seq into num tuples


empty a list

matplotlib.cbook.print_cycles(objects, outstream=<open file '<stdout>', mode 'w' at 0x7fe77cfc0150>, show_progress=False)
A list of objects to find cycles in. It is often useful to pass in gc.garbage to find the cycles that are preventing some objects from being garbage collected.
The stream for output.
If True, print the number of objects reached as they are found.
matplotlib.cbook.quad2cubic(q0x, q0y, q1x, q1y, q2x, q2y)

This function has been moved to matplotlib.mlab – please import it from there


return the memory consumed by process


reverse the dictionary – may lose data if values are not unique!


make sure args are equal len before zipping

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 give type

matplotlib.cbook.simple_linear_interpolation(a, steps)
matplotlib.cbook.soundex(name, len=4)

soundex module conforming to Odell-Russell algorithm


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(fmt='%Y-%m-%d', missing='Null', missingval=None)

Bases: matplotlib.cbook.converter

convert to a date or None

use a time.strptime() format string for conversion

class matplotlib.cbook.todatetime(fmt='%Y-%m-%d', missing='Null', missingval=None)

Bases: matplotlib.cbook.converter

convert to a datetime or None

use a time.strptime() format string for conversion

class matplotlib.cbook.tofloat(missing='Null', missingval=None)

Bases: matplotlib.cbook.converter

convert to a float or None

class matplotlib.cbook.toint(missing='Null', missingval=None)

Bases: matplotlib.cbook.converter

convert to an int or None

class matplotlib.cbook.tostr(missing='Null', missingval='')

Bases: matplotlib.cbook.converter

convert to string or None


Return a list of unique elements of x

matplotlib.cbook.unmasked_index_ranges(mask, compressed=True)

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.


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,]]

# returns array [3,4,]

ii = unmasked_index_ranges(ma.getmaskarray(y), compressed=False)
# returns array [[0, 2], [3, 5]]

# returns array [3,4,]

Prior to the transforms refactoring, this was used to support masked arrays in Line2D.

matplotlib.cbook.vector_lengths(X, P=2.0, axis=None)

This function has been moved to matplotlib.mlab – please import it from there

matplotlib.cbook.wrap(prefix, text, cols)

wrap text with prefix at length cols