Plotting functions and utilities (spynal.plots)

Functions for generating common data plots and plotting-related utilities

Overview

High-level interfaces to create plot types commonly used in neuroscience, including heat maps, line/curve plots with tranparent fills indicating errors, and offset lineseries plots (eg for plotting series of ephys traces or evoked potentials).

Also contains some utility functions useful in generating plots.

Built using matplotlib.pyplot functions.

Function list

Plot-generating functions

  • plot_line_with_error_fill : Plot 1d data as line(s) w/ transparent fill(s) to indicate errors

  • plot_heatmap : Plot 2d data as a heatmap (pseudocolor) plot

  • plot_lineseries : Plot 2d data as series of offset lines

Plotting utilities

  • full_figure : Create full-screen figure

  • savefig : Save figure to file in ~WYSIWYG manner

  • make_colormap : Create custom colormap and register name for further use

  • colorbar : Create colorbar without messing up parent axis size/shape

  • plot_markers : Plot set of markers (eg to mark trial event times) on given axis(s)

Function reference

plot_line_with_error_fill(x, data, err=None, ax=None, color=None, events=None, **kwargs)

Plot 1d data as line plot(s) +/- error(s) as semi-transparent fill(s) in given axis

Can plot multiple lines/errors with same x-axis values in same axis by inputting multiple data/error series

Uses plt.plot() and plt.fill()

Parameters:
  • x (array-like, shape=(n,)) – x-axis sampling vector for both data and err.

  • data (array-like, shape=(n,) or (n_lines,n)) – Values to plot on y-axis as line(s) (typically means or medians). To plot multiples lines with the same x-axis values, input a 2D array where each row will be plotted as a separate line.

  • err (array-like, shape=(n,) or (n_lines,n) or (2*n_lines,n), default: (no errorbars)) –

    Error values (SEMs/confints/etc.) to plot as semi-transparent fill around line(s).

    If vector-valued or (n_lines,n) array, errors are treated as 1-sided (like SEMs), and data[j,:] +/- err[j,:] is plotted for each line j.

    If given as (2*n_lines,n) array, it’s treated as 2-sided [upper; lower] error ranges (like confidence intervals), with the odd rows = upper and even rows = lower errors corresponding to each line.

    If err=None [default], only the data line(s) are plotted without error fills (to simplify calling code with optional errors).

  • color (Color spec or (n_lines,) of Color specs, default: (standard matplotlib color order)) – Color to plot each line(s) and error fill(s) in. Can input either a single color spec to use for all lines/fills, or 1 per line/fill pair. Can input in any of the ways matplotlib colors are defined (strings, 3-tuples, etc.)

  • events (callable or array-like, shape=(n_events,)) – List of event values (eg times) to plot as markers on x-axis -or- callable function that will just plot the event markers itself. See plot_markers() for details.

  • **kwargs

    Any additional keyword args are interpreted as parameters of plt.axes() (settable Axes object attributes), plt.plot() (Line2D object attributes), or plt.fill() (Polygon object attributes) and passsed to the proper function. A few commonly used options, with custom defaults:

    linewidthscalar, default: 1.5

    Width of all plotted data line(s)

    alphafloat, range=[0,1], default: 0.25

    Transparency alpha value for plotting all error fill(s). 1=fully opaque, 0=fully transparent.

Returns:

  • lines (list of Line2D objects) – ax.plot output. Allows access to line properties of line.

  • patches (list of Polygon objects) – ax.fill output. Allows access to patch properties of fill.

  • ax (Axis object) – Axis plotted into

plot_heatmap(x, y, data, ax=None, clim=None, events=None, **kwargs)

Plot 2D data as a heatmap (aka pseudocolor) plot in given axis

Uses plt.imshow()

Parameters:
  • x (array-like, shape=(n_x,)) – Sampling vector for data dimension to be plotted along x-axis

  • y (array-like, shape=(n_y,)) – Sampling vector for data dimension to be plotted along y-axis

  • data (ndarray, shape=(n_y,n_x)) – Data to plot on color axis. NOTE: Data array must be 2d, with data to be plotted on y-axis the first dimension and the x-axis data 2nd.

  • ax (Pyplot Axis object, default: plt.gca() (current axis)) – Axis to plot into.

  • clim (array-like, shape=(2,), default: (data.min(),data.max()) (full range of data)) – [low,high] limits of color axis

  • events (callable or array-like, shape=(n_events,)) – List of event values (eg times) to plot as markers on x-axis -or- callable function that will just plot the event markers itself. See plot_markers() for details.

  • **kwargs

    Any additional keyword args are interpreted as parameters of plt.axes() (settable Axes object attributes) or plt.imshow() (AxesImage object attributes). A few commonly used options, with custom defaults:

    cmapstr | Colormap object. default: ‘viridis’ (linear dark-blue to yellow colormap)

    Colormap to plot heatmap in, given either as name of matplotlib colormap or custom matplotlib.colors.Colormap object instance.

    origin{‘lower’,’upper’}, default: ‘lower’

    Where 1st value in data is plotted along y-axis: ‘lower’=bottom, ‘upper’=top.

Returns:

  • img (AxesImage object) – Output of ax.imshow(). Allows access to image properties.

  • ax (Axis object) – Axis plotted into.

plot_lineseries(x, y, data, ax=None, scale=1.5, color='C0', origin='upper', events=None, **kwargs)

Plot 2d data as series of vertically-offset line plots with same x-axis values

Used for example when plotting time-series traces from multiple electrodes on a linear probe.

Uses plt.plot()

Parameters:
  • x (array-like, shape=(n_x,)) – Sampling vector for data dimension to be plotted on x-axis. This will often be timepoints.

  • y (array-like, shape=(n_y,)) – Sampling vector for data dimension to be plotted along y-axis. Can be either numeric or string labels ot plot for y-axis ticklabels (one at each plotted line). This will often be channel numbers or channel labels.

  • data (ndarray, shape=(n_y,n_x)) – Data to plot as vertically-offset line series. NOTE: Data array must be 2d, with data to be plotted on y-axis the first dimension and the x-axis data 2nd.

  • ax (Pyplot Axis object, default: plt.gca() (current axis)) – Axis to plot into

  • scale (float, default: 1.5) – Scale factor for plotting data. 1 = max range of entire data maps to offset between successive lines in plot; >1 = extends farther; <1 = scaled smaller than offset.

  • color (Color spec | (n_y,) of Color specs, default: 'C0' (blue for all lines)) – Color(s) to use to plot each line in line series. Can input either a single color spec to use for all lines/fills, or 1 per line/fill pair. Can input in any of the ways matplotlib colors are defined (strings, 3-tuples, etc.)

  • origin ({'lower','upper'}, default: 'upper') – Where 1st value in data is plotted along y-axis;’lower’=bottom, ‘upper’=top. Default order plots in same order as a probe numbered from topmost contact.

  • events (callable or array-like, shape=(n_events,)) – List of event values (eg times) to plot as markers on x-axis -or- callable function that will just plot the event markers itself. See plot_markers() for details.

  • **kwargs

    Any additional keyword args are interpreted as parameters of plt.axes() (settable Axes object attributes) or plt.plot() (Line2D object attributes) and passsed to the proper function. A few commonly used options, with custom defaults:

    linewidthscalar, default: 1

    Width of all plotted data line

Returns:

  • lines (list of Line2D objects) – ax.plot output. Allows access to line properties of line.

  • ax (Axis object) – Axis plotted into.

full_figure(**kwargs)

Create full-screen figure

Wrapper around plt.figure() that sets size to full screen.

Parameters:

**kwargs – Any keyword args passed directly to plt.figure()

Returns:

fig – Output of plt.figure()

Return type:

Figure object

savefig(filename, fig=None, figsize=(11.0, 8.5), dpi=500, makedir=True, **kwargs)

Save figure to file in (more-or-less) WYSIWYG manner, generate target directory if missing

Wrapper around fig.savefig()

Parameters:
  • filename (str) – Full-path filename to save figure into. If no file extension included, by default we add .png (to save a PNG file).

  • fig (Pyplot Figure object, default: plt.gcf()) – Figure to save. Defaults to current figure.

  • figsize (2-tuple of float, default: default: (11.0,8.5)) – Figure dimension (width, height) in inches. Defaults to standard 8.5 x 11 in portrait.

  • dpi (float, default: 500) – Resolution of saved figure in dots per inch.

  • makedir (bool, default, True) – If True, creates requested directory to save figure into if missing

References

https://stackoverflow.com/questions/45515320/matplotlib-savefig-fullscreen

make_colormap(name=None, colors=None, register=None, **kwargs)

Create a custom colormap and register its name for later convenient use

Parameters:
  • name (str) – Name of colormap to create. If register is True, name will be registered as a matplotlib colormap, so later you can invoke it using cmap=`name`.

  • colors (callable or dict or array-like) –

    Specifies the colors in custom colormap in one of three ways:

    1. callable : colors is input as a function/lambda that generates colors under one of the two following specifications…

    2. dict : Keys = ‘red’, ‘green’, ‘blue’, and (optionally) ‘alpha’. Values for each = (n_segments-1,3) array-like of floats in range (0,1). These are anchor points for each color, and segments of colormap will be linearly interpolated between each to generate a full colormap. The first of the 3 values in each row determines where the anchor point lies in the colormap (0-1 ~ lowest to highest point). Color segements are interpolated from the 3rd value in one row to the 2nd value in the subsequent row (see LinearSegmentedColormap ref below for full explanation). Colormap generated using matplotlib.colors.LinearSegmentedColormap().

    3. array-like : List of Matplotlib color specifications, or an equivalent (n_colors,3=RGB) or (n_colors,4=RGBA) array. Specifies each color in entire colormap. Colormap generated using matplotlib.colors.ListedColormap().

  • register (bool, default: True if value given for name) – If True, name is registered as matplotlib colormap, which can later be invoked using cmap=`name`.

  • **kwargs – Any other keyword args passed directly to LinearSegmentedColormap or ListedColormap.

Returns:

cmap – Generated colormap

Return type:

matplotlib.colors.Colormap object (LinearSegmentedColormap or ListedColormap)

References

https://matplotlib.org/stable/tutorials/colors/colormap-manipulation.html https://matplotlib.org/stable/api/_as_gen/matplotlib.colors.LinearSegmentedColormap.html https://matplotlib.org/stable/api/_as_gen/matplotlib.colors.ListedColormap.html

colorbar(mappable=None, ax=None, size=0.05, pad=0.05, **kwargs)

Create a colorbar for given axis without messing up parent axis size (as plt.colorbar() does)

Wrapper around fig.colorbar

Parameters:
  • mappable (matplotlib.cm.ScalarMappable object, default: ax._gci() (current artist)) – The thing this colorbar is supposed to describe (eg the output of plt.imshow()). Defaults to current colorable artist, if available.

  • ax (Pyplot Axis object, default: plt.gca() (current axis)) – Parent axis to plot colorbar for (eg axis with image/heatmap plot)

  • size (float, default: 0.05) – Colorbar width, expressed as proportion of parent axis width

  • pad (float, default: 0.05) – Distance of colorbar from parent axis, expressed as proportion of parent axis width

  • **kwargs – Any other keyword args passed directly to fig.colorbar.

Returns:

cbar – Output of plt.colorbar(). Allows customization of colorbar properties.

Return type:

matplotlib.colorbar.Colorbar object

References

https://stackoverflow.com/questions/32462881/add-colorbar-to-existing-axis

plot_markers(values, axis='x', ax=None, xlim=None, ylim=None, linecolor=[0.5, 0.5, 0.5], linewidth=0.5, fillcolor=[0.5, 0.5, 0.5], fillalpha=0.2)

Plot set of markers on given axis/axes (eg to mark trial event times)

Single point events should be input as scalars in values, and are plotted as a single line of given color and width.

Events extending over a range/duration should be input as 2-length (start,end) tuples, in values, and are plotted as filled rectangles of given color and alpha (transparency).

Events that reflect a central value (eg mean) +/- a range or error (eg SDs) should be input as 3-length (center-error,center,center+error) tuples in values, and are plotted as a solid central line with dashed error lines, in the given color and width.

All marker types extend the full length of the opposing axis.

NOTE: If limits are explicitly input for the axis the markers are plotted on, any marker fully outside of the plot limits will not be plotted, to avoid surprise expansion of the plot limits.

Parameters:
  • values (array-like, shape=(n_events,), dtype=scalars and/or 2-tuples and/or 3-tuples) – List of values (eg trial event times) on given axes to plot markers for. Each entry in list can be a scalar (plotted as a line), a (start,end) 2-length tuple (plotted as a filled rectangle), or a (-err,center,+err) 3-length tuple (plotted as solid line with surrounding dashed lines).

  • axis ({'x','y','both'}, default: 'x') – Which axis to plot markers on – x-axis, y-axis, or both axes (eg for time x time plot)

Returns:

  • ax (Axis object) – Axis plotted into.

  • handles (List of Line2D, Polygon, or lists of Line2D objects) – plt.plot/fill outputs for each marker plotted, in the same order as input. Allows access to properties of marker lines/fills.