pyplot — Matplotlib-like plotting package

New plotting interface

This package provides a simple command line interface to the Mantid plotting functionality, resembling matplotlib and its pyplot package (http://matplotlib.org). The module is subject to changes and feedback is very much welcome!

New Python command line interface for plotting in Mantid (a la matplotlib)

The idea behind this new module is to provide a simpler, more homogeneous command line interface (CLI) to the Mantid plotting functionality. This new interface is meant to resemble matplotlib as far as possible, and to provide a more manageable, limited number of plot options.

The module is at a very early stage of development and provides limited functionality. This is very much work in progress at the moment. The module is subject to changes and feedback is very much welcome!

Simple plots can be created and manipulated with a handul of commands. See the following examples.

Plot an array (python list)

# plot array
plot([0.1, 0.3, 0.2, 4])
# plot x-y
plot([0.1, 0.2, 0.3, 0.4], [1.2, 1.3, 0.2, 0.8])

Plot an array with a different style

The plot commands that are described here accept a list of options (kwargs) as parameters passed by name. With these options you can modify plot properties, such as line styles, colors, axis scale, etc. The following example illustrates the use of a few options. You can refer to the list of options provided further down in this document. In principle, any combination of options is supported, as long as it makes sense!

a = [0.1, 0.3, 0.2, 4]
plot(a)
import numpy as np
y = np.sin(np.linspace(-2.28, 2.28, 1000))
plot(y, linestyle='-.', marker='o', color='red')

If you have used the traditional Mantid command line interface in Python you will probably remember the plotSpectrum, plotBin and plotMD functions. These are supported in this new interface as shown in the following examples.

Plot a Mantid workspace

You can pass one or more workspaces to the plot function. By default it will plot the spectra of the workspace(s), selecting them by the indices specified in the second argument. This behavior is similar to the plotSpectrum function of the traditional mantidplot module. This is a simple example that produces plots of spectra:

# first, load a workspace. You can do this with a Load command or just from the GUI menus
ws = Load("/path/to/MAR11060.raw", OutputWorkspace="foo")
# 1 spectrum plot
plot(ws, 100)
# 3 spectra plot
plot(ws, [100, 101, 102])

Different types of plots

The plot() function provides a unified interface to different types of plots, including specific graphs of spectra, bins, multidimensional workspaces, etc. These specific types of plots are explained in the next sections. plot() makes a guess as to what tool to use to plot a workspace. For example, if you pass an MD workspace it will make an MD plot. But you can request a specific type of plot by specifying a keyword argument (‘tool’). The following tools (or different types of plots) are supported:

Tool tool= parameter values (all are equivalent aliases) Old similar function
plot spectra (default) ‘plot_spectrum’, ‘spectrum’, ‘plot_sp’, ‘sp’ plotSpectrum
plot bins ‘plot_bin’, ‘bin’ plotBin
plot MD ‘plot_md’, ‘md’ plotMD

The last column of the table lists the functions that produce similar plots in the traditional MantidPlot Python plotting interface. For the time being this module only supports these types of specific plots. Note that the traditional plotting interface of MantidPlot provides support for many more specific types of plots. These or similar ones will be added in this module in future releases:

  • plot2D
  • plot3D
  • plotSlice
  • instrumentWindow
  • waterFallPlot
  • mergePlots
  • stemPlot

Plot spectra using workspace objects and workspace names

It is also possible to pass workspace names to plot, as in the following example where we plot a few spectra:

# please make sure that you use the right path and file name
mar = Load('/path/to/MAR11060.raw', OutputWorkspace="MAR11060")
plot('MAR11060', [10,100,500])
plot(mar,[3, 500, 800])

Let’s load one more workspace so we can see some examples with list of workspaces

loq=Load('/path/to/LOQ48097.raw', OutputWorkspace="LOQ48097")

The next lines are all equivalent, you can use workspace objects or names in the list passed to plot:

plot([mar, 'LOQ48097'], [800, 900])
plot([mar, loq], [800, 900])
plot(['MAR11060', loq], [800, 900])

Here, the plot function is making a guess and plotting the spectra of these workspaces (instead of the bins or anything else). You can make that choice more explicit by specifying the ‘tool’ argument. In this case we use ‘plot_spectrum’ (which also has shorter aliases: ‘spectrum’, or simply ‘sp’ as listed in the table above):

plot(['MAR11060', loq], [800, 900], tool='plot_spectrum')
plot(['MAR11060', loq], [801, 901], tool='sp')

Alternatively, you can use the plot_spectrum command, which is equivalent to the plot command with the keyword argument tool=’plot_spectrum’:

plot_spectrum(['MAR11060', loq], [800, 900])

Plotting bins

To plot workspace bins you can use the keyword ‘tool’ with the value ‘plot_bin’ (or equivalent ‘bin’), like this:

ws = Load('/path/to/HRP39182.RAW', OutputWorkspace="HRP39182")
plot(ws, [1, 5, 7, 100], tool='plot_bin')

or, alternatively, you can use the plot_bin command:

plot_bin(ws, [1, 5, 7, 100], linewidth=4, linestyle=':')

Plotting MD workspaces

Similarly, to plot MD workspaces you can use the keyword ‘tool’ with the value ‘plot_md’ (or ‘md’ as a short alias), like this:

simple_md_ws = CreateMDWorkspace(Dimensions='3',Extents='0,10,0,10,0,10',Names='x,y,z',Units='m,m,m',SplitInto='5',MaxRecursionDepth='20',OutputWorkspace=MDWWorkspaceName)
plot(simple_md_ws, tool='plot_md')

or a specific plot_md command:

plot_md(simple_md_wsws)

For simplicity, these examples use a dummy MD workspace. Please refer to the Mantid (http://www.mantidproject.org/MBC_MDWorkspaces) for a more real example, which necessarily gets more complicated and data intensive.

Changing style properties

You can modify the style of your plots. For example like this (for a full list of options currently supported, see below).

lines = plot(loq, [100, 104], tool='plot_spectrum', linestyle='-.', marker='*', color='red')

Notice that the plot function returns a list of lines, which correspond to the spectra lines. At present the lines have limited functionality. Essentially, the data underlying these lines can be retrieved as follows:

lines[0].get_xdata()
lines[0].get_ydata()

If you use plot_spectrum, the number of elements in the output lines should be equal to the number of bins in the corresponding workspace. Conversely, if you use plot_bin, the number of elements in the output lines should be equal to the number of spectra in the workspace.

To modify the figure, you first need to obtain the figure object that represents the figure where the lines are displayed. Once you do so you can for example set the title of the figure like this:

fig = lines[0].figure()
fig.suptitle('Example figure title')

Other properties can be modified using different functions, as in matplotlib’s pyplot. For example:

title('Test plot of LOQ')
xlabel('ToF')
ylabel('Counts')
ylim(0, 8)
xlim(1e3, 4e4)
xscale('log')
grid('on')

By default, these functions manipulate the current figure (the last or most recently shown figure). You can also save the current figure into a file like this:

savefig('example_saved_figure.png')

where the file format is guessed from the file extension. The same extensions as in the MantidPlot figure export dialog are supported, including jpg, png, tif, ps, and svg.

The usage of these functions very similar to the matlab and/or pyplot functions with the same names. The list of functions currently supported is provided further below.

Additional options supported as keyword arguments (kwargs):

There is a couple of important plot options that are set as keyword arguments:

Option name Values supported
error_bars True, False (default)
hold on, off

error_bars has the same meaning as in the traditional mantidplot plot functions: it defines whether error bars should be added to the plots. hold has the same behavior as in matplotlib and pyplot. If the value of hold is ‘on’ in a plot command, the new plot will be drawn on top of the current plot window, without clearing it. This makes it possible to make plots incrementally.

For example, one can add two spectra from a workspace using the following command:

lines = plot(loq, [100, 102], linestyle='-.', color='red')

But similar results can be obtained by plotting one of the spectra by a first command, and then plotting the second spectra in a subsequent command with the hold parameter enabled:

lines = plot(loq, 100, linestyle='-.', color='red')
lines = plot(loq, 102, linestyle='-.', color='blue', hold='on')

After the two commands above, any subsequent plot command that passes hold=’on’ as a parameter would add new spectra into the same plot. An alternative way of doing this is explained next. Note however that using the hold property to combine different types of plots (plot_spectrum, plot_bin, etc.) will most likely produce useless results.

Multi-plot commands

In this version of pyplot there is limited support for multi-plot commands (as in pyplot and matlab). For example, you can type commands like the following:

plot(ws, [100, 101], 'r', ws, [200, 201], 'b', tool='plot_spectrum')

This command will plot spectra 100 and 101 in red and spectra 200 and 201 in blue on the same figure. You can also combine different workspaces, for example:

plot(ws, [100, 101], 'r', mar, [50, 41], 'b', tool='plot_spectrum')

Style options supported as keyword arguments

Unless otherwise stated, these options are in principle supported in all the plot variants. These options have the same (or as closed as possible) meaning as in matplotlib.

Option name Values supported
linewidth real values
linestyle ‘-‘, ‘–’, ‘-.’ ‘.’
marker None/”None” ‘o’, ‘v’, ‘^’, ‘<’, ‘>’, ‘s’, ‘*’, ‘h’, ‘|’, ‘_’
color color character or string (‘b’, ‘blue’, ‘g’, ‘green’, ‘k’, ‘black’, ‘y’, ‘yellow’, ‘c’, ‘cyan’, ‘r’, ‘red’. ‘m’, ‘magenta’, etc.). RGB colors are not supported at the moment.

Modifying the plot axes

You can modify different properties of the plot axes via functions, as seen before. This includes the x and y axis titles, limits and scale (linear or logarithmic). For example:

ylabel('Counts')
ylim(0, 8)
yscale('log')

An alternative is to use equivalent methods provided by the Figure and Axes objects. For this you first need to retrieve the figure and axes where a plot (or line) has been shown.

lines = plot(mar,[3, 500, 800])
fig = lines[0].figure()
all_ax = fig.axes()    # fig.axes() returns in principle a list
ax = all_ax[0]         #  but we only use one axes
ax.set_ylabel('Counts')
ax.set_xlabel('ToF')
ax.set_ylim(0, 8)
ax.set_xlim(1e2, 4e4)
ax.set_xscale('log')

Functions that modify plot properties

Here is a list of the functions supported at the moment. They offer the same functionality as their counterparts in matplotlib’s pyplot.

  • title
  • xlabel
  • ylabel
  • ylim
  • xlim
  • axis
  • xscale
  • yscale
  • grid
  • savefig

This is a limited list of functions that should be sufficient for basic plots. These functions are presently provided as an example of this type of interface, and some of them provide functionality similar or equivalent to several of the keyword arguments for plot commands detailed in this documentation. Some others produce results equivalent to the more object oriented methods described above. For example, the function xlabel is equivalent to the method set_xlabel applied on the Axes object for the current figure.

This module is by default imported into the standard MantidPlot namespace. You can use the functions and classes included here without any prefix or adding this module name prefix (pymantidplot.pyplot), as in the following example:

# Two equivalent lines:
pymantidplot.pyplot.plot([1, 3, 2])
plot([1, 3, 2])

Note that the plot() function of this module has replaced the traditional plot() function of MantidPlot which has been moved into a package called qtiplot. To use it you can do as follows:

pymantidplot.qtiplot.plot('MAR11060', [800, 801])
# or if you prefer shorter prefixes:
import pymantidplot.qtiplot as qtiplt
qtiplt.plot('MAR11060', [800, 801])

Below is the reference documentation of the classes and functions included in this module.

class pymantidplot.pyplot.Axes(fig, xscale='linear', yscale='linear')

A very minimal replica of matplotlib.axes.Axes. The true Axes is a sublcass of matplotlib.artist and provides tons of functionality. At the moment this just provides a few set methods for properties such as labels and axis limits.

__init__(fig, xscale='linear', yscale='linear')
axis(lims)

Set the boundaries or limits of the x and y axes

@param lims :: list or vector specifying min x, max x, min y, max y

get_figure()

Get the figure where this Axes object is included

Returns :: figure object for the figure that contains this Axes

set_xlabel(lbl)

Set the label or title of the x axis

@param lbl :: x axis lbl

set_xlim(xmin, xmax)

Set the boundaries of the x axis

@param xmin :: minimum value @param xmax :: maximum value

set_xscale(scale_str)

Set the type of scale of the x axis

@param scale_str :: either ‘linear’ for linear scale or ‘log’ for logarithmic scale

set_ylabel(lbl)

Set the label or title of the y axis

@param lbl :: y axis lbl

set_ylim(ymin, ymax)

Set the boundaries of the y axis

@param ymin :: minimum value @param ymax :: maximum value

set_yscale(scale_str)

Set the type of scale of the y axis

@param scale_str :: either ‘linear’ for linear scale or ‘log’ for logarithmic scale

class pymantidplot.pyplot.Figure(num)

A very minimal replica of matplotlib.figure.Figure. This class is here to support manipulation of multiple figures from the command line.

__init__(num)
axes()

Obtain the list of axes in this figure.

Returns :: list of axes. Presently only one Axes object is supported
and this method returns a single object list
classmethod fig_seq()

Helper method, returns the current sequence number for figures

savefig(name)

Save current plot into a file. The format is guessed from the file extension (.eps, .png, .jpg, etc.)

@param name :: file name

suptitle(title)

Set a title for the figure

@param title :: title string

class pymantidplot.pyplot.Line2D(graph, index, x_data, y_data, fig=None)

A very minimal replica of matplotlib.Line.Line2D. The true Line2D is a sublcass of matplotlib.artist and provides tons of functionality. At the moment this just provides get_xdata(), get_ydata(), and figure() methods. It also holds its Graph object and through it it would be possible to provide additional selected functionality. Keep in mind that providing GUI line/plot manipulation functionality would require a proxy for this class.

__init__(graph, index, x_data, y_data, fig=None)
pymantidplot.pyplot.axis(lims)

Set the boundaries or limits of the x and y axes

@param lims :: list or vector specifying min x, max x, min y, max y

pymantidplot.pyplot.figure(num=None)

Return Figure object for a new figure or an existing one (if there is any with the number passed as parameter).

@param num :: figure number (optional). If empty, a new figure is created.

pymantidplot.pyplot.grid(opt='on')

Enable a grid on the active plot (horizontal and vertical)

@param title :: ‘on’ to enable

pymantidplot.pyplot.plot(*args, **kwargs)

Plot the data in various forms depending on what arguments are passed. Currently supported inputs: arrays (as Python lists or numpy arrays) and workspaces (by name or workspace objects).

@param args :: curve data and options @param kwargs :: plot line options

Returns :: the list of curves included in the plot

args can take different forms depending on what you plot. You can plot:

  • a python list or array (x) for example like this: plot(x)
  • a workspace (ws) for example like this: plot(ws, [100,101]) # this will plot spectra 100 and 101
  • a list of workspaces (ws, ws2, ws3, etc.) for example like this: plot([ws, ws2, ws3], [100,101])
  • workspaces identified by their names: plot([‘HRP39182’, ‘MAR11060.nxs’], [100,101])

You can also pass matplotlib/pyplot style strings as arguments, for example: plot(x, ‘-.’)

As keyword arguments (kwargs) you can specify multiple parameters, for example: linewidth, linestyle, marker, color.

An important keyword argument is tool. At the moment the following values are supported (they have long and short aliases):

  • To plot spectra: ‘plot_spectrum’ OR ‘spectrum’ OR ‘plot_sp’ OR ‘sp’ (default for workspaces).
  • To plot bins: ‘plot_bin’ OR ‘bin’
  • To do an MD plot: ‘plot_md’ OR ‘md’

Please see the documentation of this module (use help()) for more details.

pymantidplot.pyplot.plot_bin(workspaces, indices, *args, **kwargs)

X-Y plot of the bin counts in a workspace.

Plots one or more bin, selected by indices, using spectra numbers as x-axis and bin counts for each spectrum as y-axis.

@param workspaces :: workspace or list of workspaces (both workspace objects and names accepted) @param indices :: indices of the bin(s) to plot

Returns :: the list of curves included in the plot

pymantidplot.pyplot.plot_md(workspaces, *args, **kwargs)

X-Y plot of an MDWorkspace.

@param workspaces :: workspace or list of workspaces (both workspace objects and names accepted)

Returns :: the list of curves included in the plot

pymantidplot.pyplot.plot_spectrum(workspaces, indices, *args, **kwargs)

X-Y Plot of spectra in a workspace.

Plots one or more spectra, selected by indices, using bin boundaries as x-axis and the spectra values in each bin as y-axis.

@param workspaces :: workspace or list of workspaces (both workspace objects and names accepted) @param indices :: indices of the spectra to plot, given as a single integer or a list of integers

Returns :: the list of curves included in the plot

pymantidplot.pyplot.savefig(name)

Save current plot into a file. The format is guessed from the file extension (.eps, .png, .jpg, etc.)

@param name :: file name

pymantidplot.pyplot.title(title)

Set title of the active plot

@param title :: title string

pymantidplot.pyplot.xlabel(lbl)

Set the label or title of the x axis

@param lbl :: x axis lbl

pymantidplot.pyplot.xlim(xmin, xmax)

Set the boundaries of the x axis

@param xmin :: minimum value @param xmax :: maximum value

pymantidplot.pyplot.xscale(scale_str)

Set the type of scale of the x axis

@param scale_str :: either ‘linear’ for linear scale or ‘log’ for logarithmic scale

pymantidplot.pyplot.ylabel(lbl)

Set the label or title of the y axis

@param lbl :: y axis lbl

pymantidplot.pyplot.ylim(ymin, ymax)

Set the boundaries of the y axis

@param ymin :: minimum value @param ymax :: maximum value

pymantidplot.pyplot.yscale(scale_str)

Set the type of scale of the y axis

@param scale_str :: either ‘linear’ for linear scale or ‘log’ for logarithmic scale