pept.plots.PlotlyGrapher#

class pept.plots.PlotlyGrapher(rows=1, cols=1, xlim=None, ylim=None, zlim=None, subplot_titles=['  '])[source]#

Bases: PEPTObject

A class for PEPT data visualisation using Plotly-based 3D graphs.

The PlotlyGrapher class can create and automatically configure an arbitrary number of 3D subplots for PEPT data visualisation. They are by default set to use the alternative PEPT 3D axes convention - having the y-axis pointing upwards, such that the vertical screens of a PEPT scanner represent the xy-plane.

This class can be used to draw 3D scatter or line plots, with optional colour-coding using extra data columns (e.g. relative tracer activity or trajectory label).

It also provides easy access to the most common configuration parameters for the plots, such as axes limits, subplot titles, colorbar titles, etc. It can work with pre-computed Plotly traces (such as the ones from the pept base classes), as well as with numpy arrays.

Raises
ValueError

If xlim, ylim or zlim are not lists of length 2.

Examples

The figure is created when instantiating the class.

>>> grapher = PlotlyGrapher()
>>> lors = LineData(raw_lors...)        # Some example lines
>>> points = PointData(raw_points...)   # Some example points

Creating a trace based on a numpy array:

>>> sample_lors = lors[0]           # A numpy array of a single sample
>>> sample_points = points[0]
>>> grapher.add_lines(sample_lors)
>>> grapher.add_points(sample_points)

Showing the plot:

>>> grapher.show()

If you’d like to show the plot in your browser, you can set the default Plotly renderer:

>>> import plotly
>>> plotly.io.renderers.default = "browser"

Return pre-computed traces that you can add to other figures:

>>> PlotlyGrapher.lines_trace(lines)
>>> PlotlyGrapher.points_trace(points)

More examples are given in the docstrings of the add_points, add_lines methods.

Attributes
xlimlist or numpy.ndarray

A list of length 2, formatted as [x_min, x_max], where x_min is the lower limit of the x-axis of all the subplots and x_max is the upper limit of the x-axis of all the subplots.

ylimlist or numpy.ndarray

A list of length 2, formatted as [y_min, y_max], where y_min is the lower limit of the y-axis of all the subplots and y_max is the upper limit of the y-axis of all the subplots.

zlimlist or numpy.ndarray

A list of length 2, formatted as [z_min, z_max], where z_min is the lower limit of the z-axis of all the subplots and z_max is the upper limit of the z-axis of all the subplots.

figPlotly.Figure instance

A Plotly.Figure instance, with any number of subplots (as defined by rows and cols) pre-configured for PEPT data.

__init__(rows=1, cols=1, xlim=None, ylim=None, zlim=None, subplot_titles=['  '])[source]#

PlotlyGrapher class constructor.

Parameters
rowsint, optional

The number of rows of subplots. The default is 1.

colsint, optional

The number of columns of subplots. The default is 1.

xlimlist or numpy.ndarray, optional

A list of length 2, formatted as [x_min, x_max], where x_min is the lower limit of the x-axis of all the subplots and x_max is the upper limit of the x-axis of all the subplots.

ylimlist or numpy.ndarray, optional

A list of length 2, formatted as [y_min, y_max], where y_min is the lower limit of the y-axis of all the subplots and y_max is the upper limit of the y-axis of all the subplots.

zlimlist or numpy.ndarray, optional

A list of length 2, formatted as [z_min, z_max], where z_min is the lower limit of the z-axis of all the subplots and z_max is the upper limit of the z-axis of all the subplots.

subplot_titleslist of str, default [” “]

A list of the titles of the subplots - e.g. [“plot a)”, “plot b)”]. The default is a list of empty strings.

Raises
ValueError

If rows < 1 or cols < 1.

ValueError

If xlim, ylim or zlim are not lists of length 2.

Methods

__init__([rows, cols, xlim, ylim, zlim, ...])

PlotlyGrapher class constructor.

add_lines(lines[, row, col, width, color, ...])

Create and plot a trace for all the lines in a numpy array or pept.LineData, with possible color-coding.

add_pixels(pixels[, row, col, condition, ...])

Create and plot a trace with all the pixels in this class, with possible filtering.

add_points(points[, row, col, size, color, ...])

Create and plot a trace for all the points in a numpy array or pept.PointData, with possible color-coding.

add_trace(trace[, row, col])

Add a precomputed Plotly trace to a given subplot.

add_traces(traces[, row, col])

Add a list of precomputed Plotly traces to a given subplot.

add_voxels(voxels[, row, col, condition, ...])

Create and plot a trace for all the voxels in a pept.Voxels instance, with possible filtering.

copy([deep])

Create a deep copy of an instance of this class, including all inner attributes.

create_figure()

Create a Plotly figure, pre-configured for PEPT data.

equalise_axes()

Equalise the axes of all subplots by setting the system limits xlim and ylim to equal values, such that all data plotted is within the plotted bounds.

lines_trace(lines[, width, color, opacity, ...])

Static method for creating a Plotly trace of lines.

load(filepath)

Load a saved / pickled PEPTObject object from filepath.

points_trace(points[, size, color, opacity, ...])

Static method for creating a Plotly trace of points.

save(filepath)

Save a PEPTObject instance as a binary pickle object.

show([equal_axes])

Show the Plotly figure, optionally setting equal axes limits.

to_html(filepath[, equal_axes, include_plotlyjs])

Save the current Plotly figure as a self-contained HTML webpage.

xlabel(label[, row, col])

ylabel(label[, row, col])

zlabel(label[, row, col])

Attributes

fig

xlim

ylim

zlim

create_figure()[source]#

Create a Plotly figure, pre-configured for PEPT data.

This function creates a Plotly figure with an arbitrary number of subplots, as given in the class instantiation call. It configures them to have the y-axis pointing upwards, as per the PEPT 3D axes convention. It also sets the axes limits and labels.

Returns
figPlotly Figure instance

A Plotly Figure instance, with any number of subplots (as defined when instantiating the class) pre-configured for PEPT data.

property xlim#
property ylim#
property zlim#
property fig#
xlabel(label, row=1, col=1)[source]#
ylabel(label, row=1, col=1)[source]#
zlabel(label, row=1, col=1)[source]#
static points_trace(points, size=2.0, color=None, opacity=0.8, colorbar=True, colorbar_col=-1, colorscale='Magma', colorbar_title=None, **kwargs)[source]#

Static method for creating a Plotly trace of points. See PlotlyGrapher.add_points for the full documentation.

add_points(points, row=1, col=1, size=2.0, color=None, opacity=0.8, colorbar=True, colorbar_col=-1, colorscale='Magma', colorbar_title=None, **kwargs)[source]#

Create and plot a trace for all the points in a numpy array or pept.PointData, with possible color-coding.

Creates a plotly.graph_objects.Scatter3d object for all the points included in the numpy array or pept.PointData instance (or subclass thereof!) points and adds it to the subplot determined by row and col.

The expected data row is [time, x1, y1, z1, …].

Parameters
points(M, N >= 4) numpy.ndarray or pept.PointData

The expected data columns are: [time, x1, y1, z1, etc.]. If a pept.PointData instance (or subclass thereof) is received, the inner points will be used.

rowint, default 1

The row of the subplot to add a trace to.

colint, default 1

The column of the subplot to add a trace to.

sizefloat, default 2.0

The marker size of the points.

colorstr or list-like, optional

Can be a single color (e.g. “black”, “rgb(122, 15, 241)”) or a colorbar list. Overrides colorbar if set. For more information, check the Plotly documentation. The default is None.

opacityfloat, default 0.8

The opacity of the lines, where 0 is transparent and 1 is fully opaque.

colorbarbool, default True

If set to True, will color-code the data in the points column colorbar_col. Is overridden by color if set.

colorbar_colint, default -1

The column in points that will be used to color the points. Only has an effect if colorbar is set to True. The default is -1 (the last column).

colorscalestr, default “Magma”

The Plotly scheme for color-coding the colorbar_col column in the input data. Typical ones include “Cividis”, “Viridis” and “Magma”. A full list is given at plotly.com/python/builtin-colorscales/. Only has an effect if colorbar = True and color is not set.

colorbar_titlestr, optional

If set, the colorbar will have this title above it.

Raises
ValueError

If points is not a numpy.ndarray with shape (M, N), where N >= 4.

Notes

If a colorbar is to be used (i.e. colorbar = True and color = None) and there are fewer than 10 unique values in the colorbar_col column in points, then the points for each unique label will be added as separate traces.

This is helpful for cases such as when plotting points with labelled trajectories, as when there are fewer than 10 trajectories, the distinct colours automatically used by Plotly when adding multiple traces allow the points to be better distinguished.

Examples

Add an array of points (data columns: [time, x, y, z]) to a PlotlyGrapher instance:

>>> grapher = PlotlyGrapher()
>>> points_raw = np.array(...)      # shape (N, M >= 4)
>>> grapher.add_points(points_raw)
>>> grapher.show()

Add all the points in a PointData instance:

>>> point_data = pept.PointData(...)    # Some example data
>>> grapher.add_points(point_data)
>>> grapher.show()

If you have an extremely large number of points in a numpy array, you can plot every 10th point using slices:

>>> pts = np.array(...)         # shape (N, M >= 4), N very large
>>> grapher.add_points(pts[::10])
static lines_trace(lines, width=2.0, color=None, opacity=0.6, colorbar=True, colorbar_col=0, colorscale='Magma', colorbar_title=None)[source]#

Static method for creating a Plotly trace of lines. See PlotlyGrapher.add_lines for the full documentation.

add_lines(lines, row=1, col=1, width=2.0, color=None, opacity=0.6, colorbar=True, colorbar_col=0, colorscale='Magma', colorbar_title=None)[source]#

Create and plot a trace for all the lines in a numpy array or pept.LineData, with possible color-coding.

Creates a plotly.graph_objects.Scatter3d object for all the lines included in the numpy array or pept.LineData instance (or subclass thereof!) lines and adds it to the subplot determined by row and col.

It expects LoR-like data, where each line is defined by two points. The expected data columns are [time, x1, y1, z1, x2, y2, z2, …].

Parameters
lines(M, N >= 7) numpy.ndarray or pept.LineData

The expected data columns: [time, x1, y1, z1, x2, y2, z2, etc.]. If a pept.LineData instance (or subclass thereof) is received, the inner lines will be used.

rowint, default 1

The row of the subplot to add a trace to.

colint, default 1

The column of the subplot to add a trace to.

widthfloat, default 2.0

The width of the lines.

colorstr or list-like, optional

Can be a single color (e.g. “black”, “rgb(122, 15, 241)”) or a colorbar list. Overrides colorbar if set. For more information, check the Plotly documentation. The default is None.

opacityfloat, default 0.6

The opacity of the lines, where 0 is transparent and 1 is fully opaque.

colorbarbool, default True

If set to True, will color-code the data in the lines column colorbar_col. Is overridden if color is set. The default is True, so that every line has a different color.

colorbar_colint, default 0

The column in the data samples that will be used to color the points. Only has an effect if colorbar is set to True. The default is 0 (the first column - time).

colorscalestr, default “Magma”

The Plotly scheme for color-coding the colorbar_col column in the input data. Typical ones include “Cividis”, “Viridis” and “Magma”. A full list is given at plotly.com/python/builtin-colorscales/. Only has an effect if colorbar = True and color is not set.

colorbar_titlestr, optional

If set, the colorbar will have this title above it.

Raises
ValueError

If lines is not a numpy.ndarray with shape (M, N), where N >= 7.

Examples

Add an array of lines (data columns: [t, x1, y1, z1, x2, y2, z2]) to a PlotlyGrapher instance:

>>> grapher = PlotlyGrapher()
>>> lines_raw = np.array(...)           # shape (N, M >= 7)
>>> grapher.add_lines(lines_raw)
>>> grapher.show()

Add all the lines in a LineData instance:

>>> line_data = pept.LineData(...)      # Some example data
>>> grapher.add_lines(line_data)
>>> grapher.show()

If you have a very large number of lines in a numpy array, you can plot every 10th point using slices:

>>> lines_raw = np.array(...)       # shape (N, M >= 7), N very large
>>> grapher.add_lines(lines_raw[::10])
add_pixels(pixels, row=1, col=1, condition=<function PlotlyGrapher.<lambda>>, opacity=0.9, colorscale='Magma')[source]#

Create and plot a trace with all the pixels in this class, with possible filtering.

Creates a plotly.graph_objects.Surface object for the centres of all pixels encapsulated in a pept.Pixels instance, colour-coding the pixel value.

The condition parameter is a filtering function that should return a boolean mask (i.e. it is the result of a condition evaluation). For example lambda x: x > 0 selects all pixels that have a value larger than 0.

Parameters
pixelspept.Pixels

The pixel space, encapsulated in a pept.Pixels instance (or subclass thereof). Only pept.Pixels are accepted as raw pixels on their own do not contain data about the spatial coordinates of the pixel box.

rowint, default 1

The row of the subplot to add a trace to.

colint, default 1

The column of the subplot to add a trace to.

conditionfunction, default lambda pixels: pixels > 0

The filtering function applied to the pixel data before plotting it. It should return a boolean mask (a numpy array of the same shape, filled with True and False), selecting all pixels that should be plotted. The default, lambda x: x > 0 selects all pixels which have a value larger than 0.

opacityfloat, default 0.4

The opacity of the surface, where 0 is transparent and 1 is fully opaque.

colorscalestr, default “Magma”

The Plotly scheme for color-coding the voxel values in the input data. Typical ones include “Cividis”, “Viridis” and “Magma”. A full list is given at plotly.com/python/builtin-colorscales/. Only has an effect if colorbar = True and color is not set.

Examples

Pixellise an array of lines and add them to a PlotlyGrapher instance:

>>> grapher = PlotlyGrapher()
>>> lines = np.array(...)                   # shape (N, M >= 7)
>>> lines2d = lines[:, [0, 1, 2, 4, 5]]     # select x, y of lines
>>> number_of_pixels = [10, 10]
>>> pixels = pept.Pixels.from_lines(lines2d, number_of_pixels)
>>> grapher.add_lines(lines)
>>> grapher.add_trace(pixels.pixels_trace())
>>> grapher.show()
add_voxels(voxels, row=1, col=1, condition=<function PlotlyGrapher.<lambda>>, size=4, color=None, opacity=0.4, colorbar=True, colorscale='Magma', colorbar_title=None)[source]#

Create and plot a trace for all the voxels in a pept.Voxels instance, with possible filtering.

Creates a plotly.graph_objects.Scatter3d object for the centres of all voxels encapsulated in a pept.Voxels instance, colour-coding the voxel value. The trace is added to the subplot determined by row and col.

The condition parameter is a filtering function that should return a boolean mask (i.e. it is the result of a condition evaluation). For example lambda x: x > 0 selects all voxels that have a value larger than 0.

Parameters
voxelspept.Voxels

The voxel space, encapsulated in a pept.Voxels object.

rowint, default 1

The row of the subplot to add a trace to.

colint, default 1

The column of the subplot to add a trace to.

conditionfunction, default lambda voxel_data: voxel_data > 0

The filtering function applied to the voxel data before plotting it. It should return a boolean mask (a numpy array of the same shape, filled with True and False), selecting all voxels that should be plotted. The default, lambda x: x > 0 selects all voxels which have a value larger than 0.

sizefloat, default 4

The size of the plotted voxel points. Note that due to the large number of voxels in typical applications, the voxel centres are plotted as square points, which provides an easy to understand image that is also fast and responsive.

colorstr or list-like, optional

Can be a single color (e.g. “black”, “rgb(122, 15, 241)”) or a colorbar list. Overrides colorbar if set. For more information, check the Plotly documentation. The default is None.

opacityfloat, default 0.4

The opacity of the lines, where 0 is transparent and 1 is fully opaque.

colorbarbool, default True

If set to True, will color-code the voxel values. Is overridden if color is set.

colorscalestr, default “Magma”

The Plotly scheme for color-coding the voxel values in the input data. Typical ones include “Cividis”, “Viridis” and “Magma”. A full list is given at plotly.com/python/builtin-colorscales/. Only has an effect if colorbar = True and color is not set.

colorbar_titlestr, optional

If set, the colorbar will have this title above it.

Raises
TypeError

If voxels is not an instance of pept.Voxels or subclass thereof.

Examples

Voxellise an array of lines and add them to a PlotlyGrapher instance:

>>> grapher = PlotlyGrapher()
>>> lines = np.array(...)           # shape (N, M >= 7)
>>> number_of_voxels = [10, 10, 10]
>>> voxels = pept.Voxels(lines, number_of_voxels)
>>> grapher.add_lines(lines)
>>> grapher.add_voxels(voxels)
>>> grapher.show()
add_trace(trace, row=1, col=1)[source]#

Add a precomputed Plotly trace to a given subplot.

The equivalent of the Plotly figure.add_trace method.

Parameters
tracePlotly trace (Scatter3d)

A precomputed Plotly trace

rowint, default 1

The row of the subplot to add a trace to.

colint, default 1

The column of the subplot to add a trace to.

add_traces(traces, row=1, col=1)[source]#

Add a list of precomputed Plotly traces to a given subplot.

The equivalent of the Plotly figure.add_traces method.

Parameters
traceslist [ Plotly trace (Scatter3d) ]

A list of precomputed Plotly traces

rowint, default 1

The row of the subplot to add the traces to.

colint, default 1

The column of the subplot to add the traces to.

equalise_axes()[source]#

Equalise the axes of all subplots by setting the system limits xlim and ylim to equal values, such that all data plotted is within the plotted bounds.

copy(deep=True)#

Create a deep copy of an instance of this class, including all inner attributes.

static load(filepath)#

Load a saved / pickled PEPTObject object from filepath.

Most often the full object state was saved using the .save method.

Parameters
filepathfilename or file handle

If filepath is a path (rather than file handle), it is relative to where python is called.

Returns
pept.PEPTObject subclass instance

The loaded object.

Examples

Save a LineData instance, then load it back:

>>> lines = pept.LineData([[1, 2, 3, 4, 5, 6, 7]])
>>> lines.save("lines.pickle")
>>> lines_reloaded = pept.LineData.load("lines.pickle")
save(filepath)#

Save a PEPTObject instance as a binary pickle object.

Saves the full object state, including inner attributes, in a portable binary format. Load back the object using the load method.

Parameters
filepathfilename or file handle

If filepath is a path (rather than file handle), it is relative to where python is called.

Examples

Save a LineData instance, then load it back:

>>> lines = pept.LineData([[1, 2, 3, 4, 5, 6, 7]])
>>> lines.save("lines.pickle")
>>> lines_reloaded = pept.LineData.load("lines.pickle")
show(equal_axes=True)[source]#

Show the Plotly figure, optionally setting equal axes limits.

Note that the figure will be shown on the Plotly-configured renderer (e.g. browser, or PDF). The available renderers can be found by running the following code:

>>> import plotly.io as pio
>>> pio.renderers

If you want an interactive figure in the browser, run the following:

>>> pio.renderers.default = "browser"
Parameters
equal_axesbool, default True

Set xlim, ylim, zlim to equal ranges such that the axes limits are equalised. Only has an effect if xlim, ylim and zlim are all None. If False, the default Plotly behaviour is used (i.e. automatically use min, max for each dimension).

to_html(filepath, equal_axes=True, include_plotlyjs=True)[source]#

Save the current Plotly figure as a self-contained HTML webpage.

Parameters
filepathstr or writeable

Path or open file descriptor to save the HTML file to.

equal_axesbool, default True

Set xlim, ylim to equal ranges such that the axes limits are equalised. Only has an effect if both xlim and ylim are None. If False, the default Plotly behaviour is used (i.e. automatically use min, max for each dimension).

include_plotlyjsTrue or “cdn”, default True

If True, embed the Plotly.JS library in the HTML file, allowing the graph to be shown offline, but adding 3 MB. If “cdn”, the Plotly.JS library will be downloaded dynamically.

Examples

Add 10 random points to a PlotlyGrapher2D instance and save the figure as an HTML webpage:

>>> fig = pept.visualisation.PlotlyGrapher2D()
>>> fig.add_points(np.random.random((10, 3)))
>>> fig.to_html("random_points.html")