pypfilt.plot

Several plotting routines, built on top of matplotlib, are provided in the pypilt.plot module.

Note

matplotlib must be installed in order to use this module.

To generate plots non-interactively (i.e., without having a window appear) use the 'Agg' backend:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

See the matplotlib FAQ for more details.

Styles and colour palettes

pypfilt.plot.default_style()

The style sheet provided by pypfilt.

pypfilt.plot.apply_style(style=None)

Temporarily apply a style sheet.

Parameters:

style – The style sheet to apply (default: default_style()).

with apply_style():
    make_plots()
pypfilt.plot.n_colours(name, n)

Extract a fixed number of colours from a colour map.

Parameters:
  • name – The colour map name (or a matplotlib.colors.Colormap instance).

  • n – The number of colours required.

colours = n_colours('Blues', 3)
pypfilt.plot.brewer_qual(name)

Qualitative palettes from the ColorBrewer project: 'Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3'.

Raises:

ValueError – if the palette name is invalid.

pypfilt.plot.colour_iter(col, palette, reverse=False)

Iterate over the unique (sorted) values in an array, returning a (value, colour) tuple for each of the values.

Parameters:
  • col – The column of (unsorted, repeated) values.

  • palette – The colour map name or a list of colours.

  • reverse – Whether to sort the values in ascending (default) or descending order.

Plotting functions

pypfilt.plot.cred_ints(ax, data, x, ci, palette='Blues', **kwargs)

Plot credible intervals as shaded regions.

Parameters:
  • ax – The plot axes.

  • data – The NumPy array containing the credible intervals.

  • x – The name of the x-axis column.

  • ci – The name of the credible interval column.

  • palette – The colour map name or a list of colours.

  • **kwargs – Extra arguments to pass to Axes.plot and Axes.fill_between.

Returns:

A list of the series that were plotted.

pypfilt.plot.observations(ax, data, label='Observations', future=False, **kwargs)

Plot observed values.

Parameters:
  • ax – The plot axes.

  • data – The NumPy array containing the observation data.

  • label – The label for the observation data.

  • future – Whether the observations occur after the forecasting time.

  • **kwargs – Extra arguments to pass to Axes.plot.

Returns:

A list of the series that were plotted.

pypfilt.plot.series(ax, data, x, y, scales, legend_cols=True, **kwargs)

Add multiple series to a single plot, each of which is styled according to values in other columns.

Parameters:
  • ax – The axes on which to draw the line series.

  • data – The structured array that contains the data to plot.

  • x – The name of the column that corresponds to the x-axis.

  • y – The name of the column that corresponds to the y-axis.

  • scales

    A list of “scales” to apply to each line series; each scale is a tuple (column, kwarg, kwvals, label_fmt) where:

    • column is the name of a column in data;

    • kwarg is the name of a keyword argument passed to plot();

    • kwvals is a list of values that the keyword argument will take; and

    • label_fmt is a format string for the legend keys or a function that returns the legend key.

  • legend_cols – Whether to show each scale in a separate column.

  • **kwargs – Extra arguments to pass to Axes.plot.

Returns:

A list of the series that were plotted.

scales = [
    # Colour lines according to the dispersion parameter.
    ('disp', 'color', brewer_qual('Set1'), r'$k = {:.0f}$'),
    # Vary line style according to the background signal.
    ('bg_obs', 'linestyle', ['-', '--', ':'], r'$bg_{{obs}} = {}$'),
]
series(ax, data, 'x_col', 'y_col', scales)

Faceted plots

This package provides a base class (Plot) for plots that comprise any number of subplots, and three subclasses for specific types of plots:

  • Wrap for plots where a single variable identifies each subplot.

  • Grid for plots where two variables are used to identify each subplot.

  • Single for single plots.

The key method of these classes is Plot.subplots(), which returns an iterator that yields (axes, data) tuples for each subplot. By looping over these tuples, one set of plotting commands can be used to generate all of the subplots. For examples, see the plot_forecasts() and plot_params() functions in the Plotting the results section of Getting Started.

class pypfilt.plot.Plot(**kwargs)

The base class for plots that comprise multiple subplots.

Parameters:

**kwargs – Extra arguments to pass to pyplot.subplots.

Variables:
  • fig – The matplotlib.figure.Figure instance for the plot.

  • axs – The \(M \times N\) array of matplotlib.axes.Axes instances for each of the sub-plots (\(M\) rows and \(N\) columns).

abstract subplots()

Return an iterator that yields (axes, data) tuples for each subplot.

add_to_legend(objs, replace=False)

Add plot objects to the list of items to show in the figure legend.

Parameters:

replace – Whether to ignore objects which share a label with any object already in this list (default) or to replace such objects (set to True).

legend(**kwargs)

Add a figure legend that lists the objects registered with add_to_legend().

Parameters:

**kwargs – Extra arguments to pass to Figure.legend.

set_xlabel(text, dy, **kwargs)

Add an x-axis label that is centred across all subplots.

Parameters:
  • text – The label text.

  • dy – The vertical position of the label.

  • **kwargs – Extra arguments to pass to Figure.text.

set_ylabel(text, dx, **kwargs)

Add an y-axis label that is centred across all subplots.

Parameters:
  • text – The label text.

  • dx – The horizontal position of the label.

  • **kwargs – Extra arguments to pass to Figure.text.

expand_x_lims(xs, pad_frac=0.05, pad_abs=None)

Increase the range of the x-axis, relative to the plot data.

Parameters:
  • xs – The x-axis data.

  • pad_frac – The fractional increase in range.

  • pad_abs – The absolute increase in range.

expand_y_lims(ys, pad_frac=0.05, pad_abs=None)

Increase the range of the y-axis, relative to the plot data.

Parameters:
  • xs – The y-axis data.

  • pad_frac – The fractional increase in range.

  • pad_abs – The absolute increase in range.

scale_x_date(lbl_fmt, day=None, month=None, year=None)

Use a datetime scale to locate and label the x-axis ticks.

Parameters:
  • lbl_fmt – The strftime() format string for tick labels.

  • day – Locate ticks at every N days.

  • month – Locate ticks at every N months.

  • year – Locate ticks at every N years.

Raises:

ValueError – unless exactly one of day, month, and year is specified.

scale_y_date(lbl_fmt, day=None, month=None, year=None)

Use a datetime scale to locate and label the y-axis ticks.

Parameters:
  • lbl_fmt – The strftime() format string for tick labels.

  • day – Locate ticks at every N days.

  • month – Locate ticks at every N months.

  • year – Locate ticks at every N years.

Raises:

ValueError – unless exactly one of day, month, and year is specified.

save(filename, format, width, height, **kwargs)

Save the plot to disk (a thin wrapper for Figure.savefig).

Parameters:
  • filename – The output filename or a Python file-like object.

  • format – The output format.

  • width – The figure width in inches.

  • height – The figure height in inches.

  • **kwargs – Extra arguments for savefig; the defaults are transparent=True and bbox_inches='tight'.

class pypfilt.plot.Wrap(data, xlbl, ylbl, fac, nr=None, nc=None, **kwargs)

Faceted plots similar to those produced by ggplot2’s facet_wrap().

Parameters:
  • data – The NumPy array containing the data to plot.

  • xlbl – The label for the x-axis.

  • ylbl – The label for the y-axis.

  • fac – The faceting variable, represented as a tuple (column_name, label_fmt) where column_name is the name of a column in data and label_fmt is the format string for facet labels or a function that returns the facet label.

  • nr – The number of rows; one of nr and nc must be specified.

  • nc – The number of columns; one of nr and nc must be specified.

  • **kwargs – Extra arguments for Plot.

Raises:

ValueError – if nr and nc are both None or are both specified.

expand_x_lims(col, pad_frac=0.05, pad_abs=None)

Increase the range of the x-axis, relative to the plot data.

Parameters:
  • col – The column name for the x-axis data.

  • pad_frac – The fractional increase in range.

  • pad_abs – The absolute increase in range.

expand_y_lims(col, pad_frac=0.05, pad_abs=None)

Increase the range of the y-axis, relative to the plot data.

Parameters:
  • col – The column name for the y-axis data.

  • pad_frac – The fractional increase in range.

  • pad_abs – The absolute increase in range.

subplots(hide_axes=False, dx=0.055, dy=0.025)

Return an iterator that yields (axes, data) tuples for each subplot.

Parameters:
  • hide_axes – Whether to hide x and y axes that are not on their bottom or left edge, respectively, of the figure.

  • dx – The horizontal location for the y-axis label.

  • dy – The vertical location for the x-axis label.

class pypfilt.plot.Grid(data, xlbl, ylbl, xfac, yfac, **kwargs)

Faceted plots similar to those produced by ggplot2’s facet_grid().

Parameters:
  • data – The NumPy array containing the data to plot.

  • xlbl – The label for the x-axis.

  • ylbl – The label for the y-axis.

  • xfac – The horizontal faceting variable, represented as a tuple (column_name, label_fmt) where column_name is the name of a column in data and label_fmt is the format string for facet labels or a function that returns the facet label.

  • yfac – The vertical faceting variable (see xfac).

  • **kwargs – Extra arguments for Plot.

expand_x_lims(col, pad_frac=0.05, pad_abs=None)

Increase the range of the x-axis, relative to the plot data.

Parameters:
  • col – The column name for the x-axis data.

  • pad_frac – The fractional increase in range.

  • pad_abs – The absolute increase in range.

expand_y_lims(col, pad_frac=0.05, pad_abs=None)

Increase the range of the y-axis, relative to the plot data.

Parameters:
  • col – The column name for the y-axis data.

  • pad_frac – The fractional increase in range.

  • pad_abs – The absolute increase in range.

subplots(hide_axes=False, dx=0.055, dy=0.025)

Return an iterator that yields (axes, data) tuples for each subplot.

Parameters:
  • hide_axes – Whether to hide x and y axes that are not on their bottom or left edge, respectively, of the figure.

  • dx – The horizontal location for the y-axis label.

  • dy – The vertical location for the x-axis label.

For consistency, a class is also provided for single plots.

class pypfilt.plot.Single(data, xlbl, ylbl, **kwargs)

Faceted plots that contain only one sub-plot; i.e., a single plot that provides the same methods as faceted plots that contain many sub-plots.

Parameters:
  • data – The NumPy array containing the data to plot.

  • xlbl – The label for the x-axis.

  • ylbl – The label for the y-axis.

  • **kwargs – Extra arguments for Plot.

expand_x_lims(col, pad_frac=0.05, pad_abs=None)

Increase the range of the x-axis, relative to the plot data.

Parameters:
  • col – The column name for the x-axis data.

  • pad_frac – The fractional increase in range.

  • pad_abs – The absolute increase in range.

expand_y_lims(col, pad_frac=0.05, pad_abs=None)

Increase the range of the y-axis, relative to the plot data.

Parameters:
  • col – The column name for the y-axis data.

  • pad_frac – The fractional increase in range.

  • pad_abs – The absolute increase in range.

subplots(hide_axes=False, dx=0.055, dy=0.025)

Return an iterator that yields (axes, data) tuples for each subplot.

Parameters:
  • hide_axes – Whether to hide x and y axes that are not on their bottom or left edge, respectively, of the figure.

  • dx – The horizontal location for the y-axis label.

  • dy – The vertical location for the x-axis label.