Classes and functions to help plot and interpret experimental data
Classes:
Functions:
List that when called returns a list of the results from calling its elements.
Example:
>>> f = lambda x: lambda y: x*y
>>> l = CallList([f(2), f(3)])
>>> l(5)
[10, 15]
Return a list of the results from calling the elements of the list.
Overlay arrows with annotations on a pre-plotted line.
Arguments:
Example:
(Source code, png, hires.png, pdf)
Add horizontal lines to a set of axes with optional labels.
Arguments:
ax: Axes (matplotlib.axes.Axes object)
positions: Positions (along the x axis)
labels: List of labels for the lines
**kwargs: Line properties (propagated to matplotlib.pyplot.axhline())
E.g., color='k', linestyle='--', linewidth=0.5
Example:
(Source code, png, hires.png, pdf)
Add vertical lines to a set of axes with optional labels.
Arguments:
ax: Axes (matplotlib.axes.Axes object)
positions: Positions (along the x axis)
labels: List of labels for the lines
**kwargs: Line properties (propagated to matplotlib.pyplot.axvline())
E.g., color='k', linestyle='--', linewidth=0.5
Example:
(Source code, png, hires.png, pdf)
Return the base filename from fname.
Unlike os.path.basename(), this function strips the file extension.
Decorate a method to return an instance of the containing class.
Plot 2D scalar data on a color axis in 2D Cartesian coordinates.
This uses a uniform grid.
Arguments:
Example:
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> x, y = np.meshgrid(np.arange(0, 2*np.pi, 0.2),
... np.arange(0, 2*np.pi, 0.2))
>>> c = np.cos(x) + np.sin(y)
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> color(ax, c)
<matplotlib.image.AxesImage object at 0x...>
Exit with a message (message) and a delay of t seconds.
Example:
>>> delayed_exit()
Exiting...
Expand a file path by replacing ‘~’ with the user directory and making the path absolute.
Example:
>>> expand_path('~/Documents')
'...Documents'
where ... is ‘/home/user/’ on Linux or ‘C:Usersuser’ on Windows (and “user” is the user id).
Create a figure and set its label.
Arguments:
Example:
>>> import matplotlib.pyplot as plt
>>> fig = figure("velocity_vs_time")
>>> plt.getp(fig, 'label')
'velocity_vs_time'
Flatten a nested dictionary.
Arguments:
Example:
>>> flatten_dict(dict(a=1, b=dict(c=2, d='hello')))
{'a': 1, 'b.c': 2, 'b.d': 'hello'}
Flatten a nested list.
Arguments:
l: List (may be nested to an arbitrary depth)
If the type of l is not in ltypes, then it is placed in a list.
ltypes: Tuple (not list) of accepted indexable types
Example:
>>> flatten_list([1, [2, 3, [4]]])
[1, 2, 3, 4]
Return the pair of indices that bound a target value in a monotonically increasing vector.
Arguments:
Example:
>>> get_indices([0, 1, 2], 1.6)
(1, 2)
Return the exponent of 1000 for which the significand of a number is within the range [1, 1000).
Example:
>>> get_pow1000(1e5)
1
Load a CSV file into a dictionary.
The strings from the header row are used as dictionary keys.
Arguments:
fname: Path and name of the file
header_row: Row that contains the keys (uses zero-based indexing)
first_data_row: First row of data (uses zero-based indexing)
If first_data_row is not provided, then it is assumed that the data starts just after the header row.
types: List of data types for each column
int and float data types will be cast into a numpy.array. If types is not provided, attempts will be made to cast each column into int, float, and str (in that order).
**kwargs: Additional arguments for csv.reader()
Example:
>>> data = load_csv("examples/load-csv.csv", header_row=2)
>>> print("The keys are: %s" % list(data))
The keys are: ['Description', 'Make', 'Model', 'Price', 'Year']
Reduce a list of strings to those that match a pattern.
By default, all of the strings are returned.
Arguments:
strings: List of strings
pattern: Case-sensitive string used for matching
If re is False (next argument), then the pattern follows the Unix shell style:
Character(s) | Role |
---|---|
* | Matches everything |
? | Matches any single character |
[seq] | Matches any character in seq |
[!seq] | Matches any char not in seq |
Wildcard characters (‘*’) are not automatically added at the beginning or the end of the pattern. For example, ‘*x*’ matches all strings that contain “x”, but ‘x*’ matches only the strings that begin with “x”.
If re is True, regular expressions are used a la Python’s re module. See also http://docs.python.org/2/howto/regex.html#regex-howto.
Since re.search() is used to produce the matches, it is as if wildcards (‘.*’) are automatically added at the beginning and the end. For example, ‘x’ matches all strings that contain “x”. Use ‘^x$’ to match only the strings that begin with “x” and ‘x$’ to match only the strings that end with “x”.
Note that ‘.’ is a subclass separator in Modelica but a wildcard in regular expressions. Escape the subclass separator as ‘\.’.
re: True to use regular expressions (False to use shell style)
Example:
>>> match(['apple', 'orange', 'banana'], '*e')
['apple', 'orange']
Return a set of filenames that match a pathname pattern.
Unlike Python’s glob.glob() function, this function runs an additional expansion on matches that are directories.
Arguments:
pathnames: String or set of strings used to match files or folders
This may contain Unix shell-style patterns:
Character(s) Role * Matches everything ? Matches any single character [seq] Matches any character in seq [!seq] Matches any char not in seq
extensions: Filename pattern or set of patterns that should be used to match files in any directories generated from pathnames
These may also use the shell-style patterns above.
Example:
>>> multiglob("examples/ChuaCircuit/*/") ['examples/ChuaCircuit/1/dsres.mat', 'examples/ChuaCircuit/2/dsres.mat']
Plot 1D scalar data as points and/or line segments in 2D Cartesian coordinates.
This is similar to matplotlib.pyplot.plot() (and actually calls that function) but provides direct support for plotting an arbitrary number of curves.
Arguments:
y: List of y-axis series
x: x-axis data
If x is not provided, the y-axis series will be plotted versus its indices. If x is a single series, it will be used for all of the y-axis series. If it is a list of series, each x-axis series will be matched to a y-axis series.
ax: Axis onto which the data should be plotted.
If ax is None (default), axes are created.
label: List of labels of each series (to be used later for the legend if applied)
color: Single entry, list, or itertools.cycle() of colors that will be used sequentially
Each entry may be a character, grayscale, or rgb value.
marker: Single entry, list, or itertools.cycle() of markers that will be used sequentially
Use None for no marker. A good assortment is [‘o’, ‘v’, ‘^’, ‘<’, ‘>’, ‘s’, ‘p’, ‘*’, ‘h’, ‘H’, ‘D’, ‘d’]. All of the possible entries are listed at: http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.lines.Line2D.set_marker.
dashes: Single entry, list, or itertools.cycle() of dash styles that will be used sequentially
Each style is a tuple of on/off lengths representing dashes. Use (0, 1) for no line and (None, None) for a solid line.
**kwargs: Additional arguments for matplotlib.pyplot.plot()
Returns: List of matplotlib.lines.Line2D objects
Example:
>>> plot([range(11), range(10, -1, -1)])
[[<matplotlib.lines.Line2D object at 0x...>], [<matplotlib.lines.Line2D object at 0x...>]]
Plot 2D vector data as arrows in 2D Cartesian coordinates using a uniform grid.
Arguments:
Example:
(Source code, png, hires.png, pdf)
Perform a list of replacements on the text in a list of files.
Arguments:
fnames: Filename or list of filenames
rpl: List of replacements to make
Each entry is a tuple of (src, dest), where dest is a string that will replace the src string. Each string can use Python’s :mod:re expressions; see https://docs.python.org/2/library/re.html for details.
Example:
>>> fname = 'temp.txt'
>>> with open(fname, 'w') as f:
... __ = f.write("apple orange banana")
>>> replace([fname], [('ba(.*)', r'ba\1\1')])
>>> with open(fname, 'r') as f:
... print(f.read())
apple orange banananana
Save a figure in an image format or list of formats.
The base filename (with directory if necessary but without extension) is determined in this order of priority:
A forward slash (;/’) can be used as a path separator, even if the operating system is Windows. Folders are created as needed.
Arguments:
formats: Format or list of formats in which the figure should be saved
fname: Filename (see above)
fig: matplotlib figure or list of figures to be saved
If fig is None (default), then the current figure will be saved.
Note
In general, save() should be called before matplotlib.pyplot.show() so that the figure(s) are still present in memory.
Example:
>>> import matplotlib.pyplot as plt
>>> figure('examples/temp')
<matplotlib.figure.Figure object at 0x...>
>>> plt.plot(range(10))
[<matplotlib.lines.Line2D object at 0x...>]
>>> save()
Saved examples/temp.pdf
Saved examples/temp.png
Note
The figure() function can be used to directly create a figure with a label.
Save all open figures as images in a format or list of formats.
The directory and base filenames (without extension) are taken from the label property of the open figures. If a figure has an empty label, then a file dialog is opened to choose the filename. Note that the figure() function can be used to directly create a figure with a label.
Arguments:
Note
In general, saveall() should be called before matplotlib.pyplot.show() so that the figure(s) are still present in memory.
Example:
>>> import matplotlib.pyplot as plt
>>> figure('examples/temp')
<matplotlib.figure.Figure object at 0x...>
>>> plt.plot(range(10))
[<matplotlib.lines.Line2D object at 0x...>]
>>> saveall()
Saved examples/temp.pdf
Saved examples/temp.png
Create an array of subplots and return their axes.
Arguments:
n_plots: Number of subplots
n_rows: Number of rows of subplots
title: Title for the figure
subtitles: List of subtitles (i.e., titles for each subplot) or None for no subtitles
label: Label for the figure
This will be used as a base filename if the figure is saved.
xlabel: Label for the x-axes (only shown for the subplots on the bottom row)
xticklabels: Labels for the x-axis ticks (only shown for the subplots on the bottom row)
If None, then the default is used.
xticks: Positions of the x-axis ticks
If None, then the default is used.
ylabel: Label for the y-axis (only shown for the subplots on the left column)
yticklabels: Labels for the y-axis ticks (only shown for the subplots on the left column)
If None, then the default is used.
yticks: Positions of the y-axis ticks
If None, then the default is used.
ctype: Type of colorbar (None, ‘vertical’, or ‘horizontal’)
clabel: Label for the color- or c-bar axis
left: Left margin
right: Right margin (ignored if cbar_orientation is ‘vertical’)
bottom: Bottom margin (ignored if cbar_orientation is ‘horizontal’)
top: Top margin
cbar: Margin reserved for the colorbar (right margin if cbar_orientation is ‘vertical’ and bottom margin if cbar_orientation is ‘horizontal’)
hspace: Horizontal space between columns of subplots
vspace: Vertical space between rows of subplots
cbar_space: Space between the subplot rectangles and the colorbar
If cbar is None, then this is ignored.
cbar_width: Width of the colorbar if vertical (or height if horizontal)
If cbar is None, then this is ignored.
Returns:
Example:
(Source code, png, hires.png, pdf)
If helpful, apply an offset and a factor to the x axis.
Arguments:
ax: Axes (matplotlib.axes.Axes object)
eagerness: Parameter to adjust how little of an offset is allowed before the label will be recentered
- 0: Offset is never applied.
- 1: Offset is always applied if it will help.
Example:
(Source code, png, hires.png, pdf)
If helpful, apply an offset and a factor to the y axis.
Arguments:
ax: Axes (matplotlib.axes.Axes object)
eagerness: Parameter to adjust how little of an offset is allowed before the label will be recentered
- 0: Offset is never applied.
- 1: Offset is always applied if it will help.
Example:
(Source code, png, hires.png, pdf)
Return the SI prefix for a power of 1000.
Return a tree of strings as a nested dictionary.
The levels of hierarchy in each string are marked with separator. The keys in the dictionary are the sub-branch names. The value at the end of each branch is the full string.
Arguments:
strings: List of strings
separator: String that marks a level of hierarchy
container: Dictionary-like class used for the results
To keep the order of the list for the tree, use collections.OrderedDict.
Example:
>>> tree(['a.b.c', 'd.e', 'd.f'])
{'a': {'b': {'c': 'a.b.c'}}, 'd': {'e': 'd.e', 'f': 'd.f'}}
Ask a yes/no question and return True if the answer is ‘Y’ or ‘y’.
Arguments:
Example:
>>> if yes("Do you want to print hello (y/n)?"):
... print("hello")
A matplotlib subclass to draw an arrowhead on a line
Arguments:
Example:
(Source code, png, hires.png, pdf)