Basic methods to help plot and interpret experimental data
Named tuple class for a constant physical quantity
The factor and then the offset are applied to the number to arrive at the quantity expressed in terms of the unit.
Return a nicely formatted representation string
Alias for field number 1
Alias for field number 0
Alias for field number 2
Alias for field number 3
Overlay arrows with annotations on top of a pre-plotted line.
Arguments:
Example:
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from modelicares import *
>>> # Create a plot.
>>> figure('examples/add_arrows')
<matplotlib.figure.Figure object at 0x...>
>>> x = np.arange(100)
>>> p = plt.plot(x, np.sin(x/4.0))
>>> # Add arrows and annotations.
>>> add_arrows(p[0], x_locs=x.take(np.arange(20,100,20)),
... label="Incr. time", xstar_offset=-0.15)
>>> saveall()
Saved examples/add_arrows.pdf
Saved examples/add_arrows.png
>>> plt.show()
Add horizontal lines to a set of axes with optional labels.
Arguments:
ax: Axes (matplotlib.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:
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from modelicares import *
>>> # Create a plot.
>>> figure('examples/add_hlines')
<matplotlib.figure.Figure object at 0x...>
>>> x = np.arange(100)
>>> y = np.sin(x/4.0)
>>> plt.plot(x, y)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-1.2, 1.2])
(-1.2, 1.2)
>>> # Add horizontal lines and labels.
>>> add_hlines(positions=[min(y), max(y)], labels=["min", "max"],
... color='r', ls='--')
>>> saveall()
Saved examples/add_hlines.pdf
Saved examples/add_hlines.png
>>> plt.show()
Add vertical lines to a set of axes with optional labels.
Arguments:
ax: Axes (matplotlib.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:
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from modelicares import *
>>> # Create a plot.
>>> figure('examples/add_vlines')
<matplotlib.figure.Figure object at 0x...>
>>> x = np.arange(100)
>>> y = np.sin(x/4.0)
>>> plt.plot(x, y)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-1.2, 1.2])
(-1.2, 1.2)
>>> # Add horizontal lines and labels.
>>> add_vlines(positions=[25, 50, 75], labels=["A", "B", "C"],
... color='k', ls='--')
>>> saveall()
Saved examples/add_vlines.pdf
Saved examples/add_vlines.png
>>> plt.show()
Encode a series of PNG images as a MPG movie.
Arguments:
imagebase: Base filename for the PNG images
The images should be located in the current directory as an “imagebase**xx.png” sequence, where xx is a frame index.
fname: Filename for the movie
”.mpg” will be appended if necessary.
fps: Number of frames per second
clean: True, if the PNG images should be deleted afterward
Note
This function requires mencoder. On Linux, install it with the following command: sudo apt-get install mencoder. Currently, this function is not supported on Windows.
Example:
import matplotlib.pyplot as plt
from numpy.random import rand
from modelicares import *
# Create the frames.
fig = plt.figure(figsize=(5,5))
ax = fig.add_subplot(111)
for i in range(50): # 50 frames
ax.cla()
ax.imshow(rand(5,5), interpolation='nearest')
fname = '_tmp%02d.png' % i
print("Saving frame %i (file %s)" % (i, fname))
fig.savefig(fname) # doctest: +ELLIPSIS
# Assemble the frames into a movie.
animate(clean=True)
Close all open figures.
This is a shortcut for the following:
>>> from matplotlib._pylab_helpers import Gcf
>>> Gcf.destroy_all()
Plot 2D scalar data on a color axis in 2D Cartesian coordinates.
This uses a uniform grid.
Arguments:
Example:
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from modelicares import *
>>> figure('examples/color')
<matplotlib.figure.Figure object at 0x...>
>>> 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)
>>> ax = plt.subplot(111)
>>> color(ax, c)
<matplotlib.image.AxesImage object at 0x...>
>>> saveall()
Saved examples/color.pdf
Saved examples/color.png
>>> plt.show()
Convert the expression of a physical quantity between units.
Arguments:
Example:
>>> from modelicares import *
>>> T = 293.15 # Temperature in K
>>> T_degC = convert(Quantity(T, factor=1, offset=-273.15, unit='C'))
>>> print(str(T) + " K is " + str(T_degC) + " degC.")
293.15 K is 20.0 degC.
Expand a file path by replacing ‘~’ with the user directory and making the path absolute.
Example:
>>> from modelicares import *
>>> expand_path('~/Documents')
'...Documents'
>>> # where ... is '/home/user/' on Linux or 'C:\Users\user\' on
>>> # Windows (and "user" is the user id).
Create a figure and set its label.
Arguments:
Example:
>>> fig = figure("velocity_vs_time")
>>> plt.getp(fig, 'label')
'velocity_vs_time'
Note
The label property is used as the base filename in the saveall() method.
Flatten a nested dictionary.
Arguments:
Example:
>>> from modelicares import *
>>> 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:
>>> from modelicares import *
>>> flatten_list([1, [2, 3, [4]]])
[1, 2, 3, 4]
Return the the pair of indices that bound a target value in a monotonically increasing vector.
Arguments:
Example:
>>> from modelicares import *
>>> get_indices([0,1,2],1.6)
(1, 2)
Return the exponent of 10 for which the significand of a number is within the range [1, 10).
Example:
>>> get_pow10(50)
1
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: Propagated to csv.reader()
Example:
>>> from modelicares import *
>>> data = load_csv("examples/load-csv.csv", header_row=2)
>>> print("The keys are: %s" % data.keys())
The keys are: ['Price', 'Description', 'Make', 'Model', 'Year']
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 method), but provides direct support for plotting an arbitrary number of curves.
Arguments:
y: y-axis data
This may contain multiple series.
x: x-axis data
If x is not provided, the y-axis data 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 (1,0) for a solid line.
**kwargs: Propagated to matplotlib.pyplot.plot()
Returns: List of matplotlib.lines.Line2D objects
Example:
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from modelicares import *
>>> figure('examples/plot')
<matplotlib.figure.Figure object at 0x...>
>>> ax = plt.subplot(111)
>>> plot([range(11), range(10, -1, -1)], ax=ax)
[[<matplotlib.lines.Line2D object at 0x...>], [<matplotlib.lines.Line2D object at 0x...>]]
>>> saveall()
Saved examples/plot.pdf
Saved examples/plot.png
>>> plt.show()
Plot 2D vector data as arrows in 2D Cartesian coordinates.
Uses a uniform grid.
Arguments:
Example:
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from modelicares import *
>>> figure('examples/quiver')
<matplotlib.figure.Figure object at 0x...>
>>> x, y = np.meshgrid(np.arange(0, 2*np.pi, 0.2),
... np.arange(0, 2*np.pi, 0.2))
>>> u = np.cos(x)
>>> v = np.sin(y)
>>> ax = plt.subplot(111)
>>> quiver(ax, u, v)
<matplotlib.quiver.Quiver object at 0x...>
>>> saveall()
Saved examples/quiver.pdf
Saved examples/quiver.png
>>> plt.show()
Save the current figures as images in a format or list of formats.
The directory and base filenames are taken from the label property of the figures. A slash (“/”) can be used as a path separator, even if the operating system is Windows. Folders are created as needed. If the label property is empty, then a directory dialog is opened to chose a directory.
Arguments:
formats: Format or list of formats in which the figure should be saved
fbase: Default directory and base filename
This is used if the label attribute of the figure is empty (‘’).
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
>>> from modelicares import *
>>> figure('temp_plot')
<matplotlib.figure.Figure object at 0x...>
>>> plt.plot(range(10))
[<matplotlib.lines.Line2D object at 0x...>]
>>> save()
Saved temp_plot.pdf
Saved temp_plot.png
Note
The figure() method 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 are taken from the label property of the figures. A slash (“/”) can be used as a path separator, even if the operating system is Windows. Folders are created as needed. If the label property is empty, then a directory dialog is opened to chose a directory. In that case, the figures are saved as a sequence of numbers.
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
>>> from modelicares import *
>>> figure('temp_plot')
<matplotlib.figure.Figure object at 0x...>
>>> plt.plot(range(10))
[<matplotlib.lines.Line2D object at 0x...>]
>>> saveall()
Saved temp_plot.pdf
Saved temp_plot.png
Note
The figure() method can be used to directly create a figure with a label.
Create an array of subplots and return their axes.
Arguments:
n_plots: Number of (sub)plots
n_rows: Number of rows of (sub)plots
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
margin_left: Left margin
margin_right: Right margin (ignored if cbar_orientation == 'vertical')
margin_bottom: Bottom margin (ignored if cbar_orientation == 'horizontal')
margin_top: Top margin
margin_cbar: Margin reserved for the colorbar (right margin if cbar_orientation == 'vertical' and bottom margin if cbar_orientation == 'horizontal')
wspace: The amount of width reserved for blank space between subplots
hspace: The amount of height reserved for white space between 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:
>>> import matplotlib.pyplot as plt
>>> from modelicares import *
>>> setup_subplots(4, 2, label='examples/setup_subplots')
([<matplotlib.axes.AxesSubplot object at 0x...>, <matplotlib.axes.AxesSubplot object at 0x...>, <matplotlib.axes.AxesSubplot object at 0x...>, <matplotlib.axes.AxesSubplot object at 0x...>], 2)
>>> saveall()
Saved examples/setup_subplots.pdf
Saved examples/setup_subplots.png
>>> plt.show()
Apply an offset and a factor as necessary to the x axis.
Arguments:
ax: matplotlib.axes object
eagerness: Parameter to adjust how little of an offset is required before the label will be recentered
- 0: Offset is never applied.
- 1: Offset is always applied if it will help.
Example:
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from texunit import label_number
>>> from modelicares import *
>>> # Generate some random data.
>>> x = np.linspace(55478, 55486, 100) # Small range and large offset
>>> xlabel = label_number('Time', 's')
>>> y = np.cumsum(np.random.random(100) - 0.5)
>>> # Plot the data.
>>> ax = setup_subplots(2, 2, label='examples/shift_scale_x')[0]
>>> for a in ax:
... a.plot(x, y)
... a.set_xlabel(xlabel)
[<matplotlib.lines.Line2D object at 0x...>]
<matplotlib.text.Text object at 0x...>
[<matplotlib.lines.Line2D object at 0x...>]
<matplotlib.text.Text object at 0x...>
>>> # Shift and scale the axes.
>>> ax[0].set_title('Original plot')
<matplotlib.text.Text object at 0x...>
>>> ax[1].set_title('After applying offset and factor')
<matplotlib.text.Text object at 0x...>
>>> shift_scale_x(ax[1])
>>> saveall()
Saved examples/shift_scale_x.pdf
Saved examples/shift_scale_x.png
>>> plt.show()
Apply an offset and a factor as necessary to the y axis.
Arguments:
ax: matplotlib.axes object
eagerness: Parameter to adjust how little of an offset is required before the label will be recentered
- 0: Offset is never applied.
- 1: Offset is always applied if it will help.
Example:
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from texunit import label_number
>>> from modelicares import *
>>> # Generate some random data.
>>> x = range(100)
>>> y = np.cumsum(np.random.random(100) - 0.5)
>>> y -= y.min()
>>> y *= 1e-3
>>> y += 1e3 # Small magnitude and large offset
>>> ylabel = label_number('Velocity', 'mm/s')
>>> # Plot the data.
>>> ax = setup_subplots(2, 2, label='examples/shift_scale_y')[0]
>>> for a in ax:
... a.plot(x, y)
... a.set_ylabel(ylabel)
[<matplotlib.lines.Line2D object at 0x...>]
<matplotlib.text.Text object at 0x...>
[<matplotlib.lines.Line2D object at 0x...>]
<matplotlib.text.Text object at 0x...>
>>> # Shift and scale the axes.
>>> ax[0].set_title('Original plot')
<matplotlib.text.Text object at 0x...>
>>> ax[1].set_title('After applying offset and factor')
<matplotlib.text.Text object at 0x...>
>>> shift_scale_y(ax[1])
>>> saveall()
Saved examples/shift_scale_y.pdf
Saved examples/shift_scale_y.png
>>> plt.show()
A matplotlib subclass to draw an arrowhead on a line
Initialize the line and arrow.
Arguments:
Example:
>>> import matplotlib.pyplot as plt
>>> from modelicares import *
>>> fig = figure('examples/ArrowLine')
>>> ax = fig.add_subplot(111, autoscale_on=False)
>>> t = [-1,2]
>>> s = [0,-1]
>>> line = ArrowLine(t, s, color='b', ls='-', lw=2, arrow='>',
... arrowsize=20)
>>> ax.add_line(line)
<modelicares.base.ArrowLine object at 0x...>
>>> ax.set_xlim(-3, 3)
(-3, 3)
>>> ax.set_ylim(-3, 3)
(-3, 3)
>>> saveall()
Saved examples/ArrowLine.pdf
Saved examples/ArrowLine.png
>>> plt.show()