Sphinx logo

plotting – astronomy-oriented matplotlib and mayavi plotting tools

The plotting module contains classes and funtions to aid in making plots useful for astrophysics.

The 2D plots in this module all use the matplotlib package, while 3d plots are a mix of matplotlib and mayavi .


In this module and all other places astropysics uses matplotlib,

Module API

class astropysics.plotting.ScatterLasso(ax=None, xys=None)

Bases: object

getLastKeys(d=None, xattr='x', yattr='y')
matchLastXYs(xyin, map=None)

takes the last set of xys and matches them to an NX2 array of x,y values, returning indecies into the 1st dimension

astropysics.plotting.add_mapped_axis(mapfunc, majorticks=5, minorticks=0, axis='x', label='', labelprops={}, args=(), fmt='%3.1f', minfmt=None, invfunc=None)

mapfunc should accept a 1D numpy array as the first argument, and the args tuple will be passed as the rest of the arguments. It should return an array of the same length as the first argument.

majorticks is the number of major ticks in the interval, while minorticks is the number of ticks between each majortick

invfunc, if present, is used to make a linearly-spaced axis

fmt and minfmt are either format specifiers for the value along the axis, or ‘sci%?’ or ‘pow%?’ to use scientific notation

if fmt is ‘log#’ or ‘ln’, a logarithmic axis will be assumed with the base given by #, and minfmt is ignored. (the function then just provides the edges)

astropysics.plotting.ax3d_animate(azels, nframes, fn, fig=None, initazel=None, relative=True, predelete=False, verbose=False, savekwargs={})

Animates a figure made in matplotlib using the mplot3d 3D plotting tools.

  • azels (sequence of (azim,elev) tuples) – Specifies the azimuth ane elevation to use for the key frames - each segment will have nframes and linearly interpolate azimuth and elevation between the azels values. If relative is True, the values are offsets (in degrees) from the previous key frame. Otherwise, they are absolute values (in degrees). If equal in length to nframes, the initial frame is chosen based on the azim and elev when the function is called. If len(nframes) == len(nazels)-1, the initial frame is taken to be the first in azels (absolute, regardless of the relative keyword value).
  • nframes (sequence of ints) – Number of frames per segment (see azels for lengths).
  • fn (string or None) – The filename to use to save the animation frames. If the substring ‘{fnum}’ appears anywhere in this name, the frame number will be added there. Otherwise, the frame number is added before the extension. If None, no files are actually saved - the animation just plays in the window.
  • fig (matplotlib.figure.Figure object, int, or None) – The figure to use for the animation.
  • relative (bool) – If True, ` azels`are relative to previous frame. Otherwise, they are absolute.
  • predelete (bool) – If True, all files matching the pattern will be deleted before saving of a new set of frames occurs.
  • verbose (bool) – If True, info is printed for each frame.
  • savekwargs (dict) – keyword arguments for matplotlib.pyplot.savefig()
  • ValueError – If azels and nframes don’t have valid lengths
  • TypeError – If the current figure doesn’t have one Axes3D
astropysics.plotting.cumulative_plot(data, Nlt=True, frac=False, xlabel='x', edges=(None, None), logx=False, logy=False, doplot=True, perr=False, **kwargs)

Plots a 1d sequence of data points as a cumulative count less than (or greater than) a given value - i.e. the integrated histogram.

  • data (array-like) – input data for plot
  • Nlt (bool) – If True, produces N(<x) plot, otherwise N(>x).
  • frac (bool or scalar) – If False, the raw N will be plotted. If True, the cumulative fraction will be plotted(e.g. it will always terminate at 1), or if a scalar, the fraction will be multiplied by that value.
  • xlabel (string) – Label for the data value.
  • edges (tuple of scalars or Nones) – Specifies the lower and upper limits for the plot. If not provided, the lowest and highest of data will be used. If data is below or above these edges, it will be ignored.
  • logx (bool) – Logarithmic x-axis?
  • logy (bool) – Logarithmic y-axis?
  • doplot (bool) – If True, the plotting function is called. Otherwise no plot is made, but the x and y values are still generated and returned (allowing for more customized plots).
  • perr – If True, shaded error regions are added assuming poisson errors. Can be a dict giving kwargs for matplotlib.pyplot.fill_between().

kwargs are passed into matplotlib.pyplot.plot()

Returns:(val,N) i.e. the x and y values of the resulting plot.
astropysics.plotting.dual_value_plot(x, y1, y2, fmt='-o', yerrs=None, xerrs=None, **kwargs)

plots dual-valued functions kwargs go to errorbar function

astropysics.plotting.logerrplot(x, y, xerr=None, yerr=None, logaxes='y', boundscale=0.5, **kwargs)

fixes log plots to be upper bounds in the event of zero-data or errorbars that go below zero

logaxes can be ‘x’,’y’,or,’xy’

astropysics.plotting.make_movie(frfn, moviefn, framerate=30, bitrate='200k', inops=None, outops=None, run=True)

Given a base file name where movie frame files have been saved, generates a movie using ffmpeg. This is intended to be used with the *_animate() functions in this module, but can be used for any set of filenames that follow the correct pattern and define movie frames.

ffmpeg must be installed for this function to work.

  • frfn (string) – The filename to use to locate the animation frames. If the substring ‘{fnum}’ appears anywhere in this name, the frame number will be added there. Otherwise, the frame number is added before the extension. This is the same form as the same as the input to ax3d_animate() or mlab_animate_rotzoom().
  • moviefn (string) – Filename to use for the output movie
  • inops (dict or None) – dictionary mapping ffmpeg options to their values for input
  • outops (dict or None) – dictionary mapping ffmpeg options to their values for output
  • run (bool) – If True, ffmpeg is actually called. Otherwise, no movie is made, but the returned string can be executed at the command line.

A string with the command line call to ffmpeg

Raises ValueError:

If the ffmpeg call does not complete sucessfully or there are no matching files.

astropysics.plotting.mlab_anaglyph(dostereo=True, anasat=0, anamask=[4, 3])

Switch enthought.mayavi.mlab to use “checkerboard” style stereo

  • dostereo (bool) – Turns on stereo if True, off if False, or if None, toggles stereo mode.
  • anasat (float) – saturation for anaglyph mode
  • anamask (2-sequence) – color mask for anaglyph mode

the VTK render window object

astropysics.plotting.mlab_animate_rotzoom(fnbase, azs=None, els=None, rolls=None, dists=None, relative=True, fps=None, ui=False, figsize=None)

This generates an animation using the mlab.animate() mechanism that rotates the scene and possibly zooms in and out with a fixed focal point.

  • azs – A sequence of azimuthal angles (in degrees), a single angle to apply on every frame, or None to not change the angle.
  • els – A sequence of elevation angles (in degrees), a single angle to apply on every frame, or None to not change the angle.
  • rolls – A sequence of roll angles (in degrees), a single angle to apply on every frame, or None to not change the angle.
  • dists – A sequence of distances, a single angle to apply on every frame, or None to not change the angle.
  • relative (bool) – If True, the azs,`els`, and rolls angles are relative to the current orientation, and dists is a multiple of the current distance. Otherwise, the quantities are absolute angles and distances.
  • fnbase – The filename for the files (_### will be added between the extension and filename) or None to just show the animation and not save. The file type will be inferred from the extension, but if no extension is given, .png will be used.
  • fps – Sets the approximate number of frames per second for the animation as it plays - set to None for no delay between frames.
  • ui (bool) – If True, a GUI will be available while the animation is running to pause or stop the animation. If False, the GUI will not be shown.
  • figsize – The resolution at which to save the figure as a (xpix,ypix) tuple or None to just use the window size.

(anim,fnlist) anim is an animator of the sort that mlab.animate() returns – call this animator to start the animation. fnlist is a list of filenames that have been saved - it will initially be empty, but once the animation is run, it will be populated.

astropysics.plotting.mlab_camera(fp=None, pos=None, angle=None, dorender=True)

Adjust enthought.mayavi.mlab camera based on a position and focal point rather than angles as used by enthought.mayavi.mlab.() .

  • fp – An (x,y,z) sequence for the focal point or None to leave alone.
  • pos – An (x,y,z) sequence for the camera position or None to leave alone.
  • angle – The field-of-view angle in degrees or None to leave alone.
  • dorender (bool) – If True, the scene will be re-rendered at the end of this function.

The VTK Camera object


Switch enthought.mayavi.mlab to use “checkerboard” style stereo

Parameters:dostereo – Turns on stereo if True, off if False, or if None, toggles stereo mode.
Returns:the VTK render window object
astropysics.plotting.mpl_context(*args, **kwds)

Used for with statements containing matplotlib plots. Usage:

with _mpl_context() as plt:
  • show (bool) – If True,:func:pyplot.show will be called when plotting is completed. This blocks execution until the user closes the plotting window.
  • clf (bool) – If True, the figure will be cleared before plotting.
  • savefn – A string to save the figure to via the matplotlib.pyplot.savefig() function, or None to not save the figure.
astropysics.plotting.mvi_texture(s, texture, genmode='plane')

Generates a texture and applies it to a mayavi surface.

  • s – A enthought.mayavi.modules.surface.Surface object or None to only load the texture.
  • texture – A enthought.mayavi.sources.api.ImageReader object or a file name for an image to be used as the texture.
  • genmode – The tcoord_generator_mode to use. Should be ‘none’ or ‘cylinder’ or ‘sphere’ or ‘plane’. Ignored if s is None. See enthought.mayavi.modules.surface.Surface docs for more details.

The enthought.mayavi.modules.surface.Surface object

astropysics.plotting.plot_histogram(nbin, binedges, **kwargs)

Uses the ‘steps’ line style to make histograms from bin data like that output from numpy.histogram(). While similar in functionality to matplotlib.pyplot.hist(), it allows the histogram data to be modfied instead of being computed in the function and accepts keywords like matplotlib.pyplot.plot().

  • nbin – Number of histogram items in each bin.
  • binedges – Edge values for bins, should be of size len(nbin)+1.

Additional keywords are passed into matplotlib.pyplot.plot().

astropysics.plotting.scatter4d(x, y, c, s, xe=None, ye=None, logax=(False, False, False, False), scaling=(1, 1, 1, 1), outlines=True, cb=True, errkwargs={}, **kwargs)

cb can be used to specify the label of the colorbar

returns collection,maskinds

astropysics.plotting.scatter_density(x, y, bins=20, threshold=None, ncontours=None, contf=False, cb=False, clf=True, bingrid=False, xlog=False, ylog=False, points=False, lims=None, skwargs={}, ckwargs={})

plots x vs. y, scatter plotting where the number is below the threshold, contouring if above

bins is the number of bins or [xbins,ybins]

ncontours defaults to bins/3

threshold defaults to whatever fills half the histogram

lims can be None or (xmin,xmax,ymin,ymax)

skwargs goes into scatter(), ckwargs goes into contour() or contourf()


This function will likely be adapted to use matplotlib.pyplot.hexbin() in the near future instead of contour or contourf, so don’t expect it to stay consistent until that happens

astropysics.plotting.scatter_panel(p, plims, x, y, c=None, s=20, xe=None, ye=None, logax=(False, False, False, False), scaling=(1, 1, 1, 1), pcfg=None, outlines=True, cb=True, xlab='', ylab='', plab='', xls=None, yls=None, errkwargs={}, fitline=False, tsize=14, **kwargs)

pcfg is a 2-tuple of the form (rows,cols)

kwargs go into pyplot.scatter

fitline can be False/True or a dictionary that has line props and an optional ‘annotate’ key word for annotation (also ‘asize’ sets font size)

astropysics.plotting.scatter_select(*args, **kwargs)

quick scatter plot to lasso objects and return an object that will be updated with the selections

args and kwargs go into matplotlib scatter except for ‘close’ which is used to close the current figure on function call(default True)

returns a dictionary that will be populated with ‘i’,’xis’, and’yi’ , and possibly ‘ci’ or ‘si’ if c or s are in the scatter plot

astropysics.plotting.split_histograms(vals, edgevals, edges, bins=None, clf=True, colors=None, styles=None, edgename='', **kwargs)

Generates histograms in the first parameter that are split over ranges based on a second parameter.

  • vals (array-like) – values for generating the histograms
  • edgevals (array-like) – values to use for splitting the histograms
  • edges (sequence with len>1) – A sequence of values giving the boundaries in the edgeval space for each of the histograms (lower bound is inclusive). Must be monotonically increasing.
  • bins – Bins for the vals following the form of matplotlib.pyplot.hist(). If None or an integer, the bins will be inferred from the full data set.
  • clf (bool) – if True, the current figure will be cleared before plotting
  • colors – line colors for each histogram or None for default
  • styles (sequnce of strings or None) – line styles for each of the histograms or None for default
  • edgename (string) – Name of the variable for the edges (used in legend)

kwargs are passed into the calls to matplotlib.pyplot.hist()


returns (nrows,ncolumns) to optimize the space for n panels

astropysics.plotting.subplots_adjust_points(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None, fig=None)

Performs the same operation as matplotlib.pyplot.subplots_adjust() but uses point size uinits instead of fractions of the total figure size.