pept.plots.PlotlyGrapher2D#
- class pept.plots.PlotlyGrapher2D(rows=1, cols=1, xlim=None, ylim=None, subplot_titles=[' '], **kwargs)[source]#
Bases:
object
A class for PEPT data visualisation using Plotly-based 2D graphs.
The PlotlyGrapher class can create and automatically configure an arbitrary number of 2D subplots for PEPT data visualisation.
This class can be used to draw 2D 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.
Examples
The figure is created when instantiating the class.
>>> import numpy as np >>> from pept.visualisation import PlotlyGrapher2D
>>> grapher = PlotlyGrapher2D() >>> lines = np.random.random((100, 5)) # columns [t, x1, y1, x2, y2] >>> points = np.random.random((100, 3)) # columns [t, x, y]
Creating a trace based on a numpy array:
>>> grapher.add_lines(lines) >>> grapher.add_points(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:
>>> PlotlyGrapher2D.lines_trace(lines) >>> PlotlyGrapher2D.points_trace(points)
More examples are given in the docstrings of the add_points, add_lines methods.
- Attributes
- xlim
list
ornumpy.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.
- ylim
list
ornumpy.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.
- fig
Plotly.Figure
instance
A Plotly.Figure instance, with any number of subplots (as defined by rows and cols) pre-configured for PEPT data.
- xlim
- __init__(rows=1, cols=1, xlim=None, ylim=None, subplot_titles=[' '], **kwargs)[source]#
PlotlyGrapher class constructor.
- Parameters
- rows
int
, optional The number of rows of subplots. The default is 1.
- cols
int
, optional The number of columns of subplots. The default is 1.
- xlim
list
ornumpy.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.
- ylim
list
ornumpy.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.
- subplot_titles
list
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.
- rows
- Raises
ValueError
If rows < 1 or cols < 1.
ValueError
If xlim or ylim are not lists of length 2.
Methods
__init__
([rows, cols, xlim, ylim, ...])PlotlyGrapher class constructor.
add_image
(image, **kwargs)Create and plot a go.Image trace.
add_lines
(lines[, row, col, width, color, ...])Create and plot a trace for all the lines in a numpy array, with possible color-coding.
add_pixels
(pixels[, row, col, colorscale, ...])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, with possible color-coding.
add_timeseries
(points[, rows_cols, size, ...])Add a timeseries plot for each dimension in points vs.
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.
create_figure
(**kwargs)Create a Plotly figure, pre-configured for PEPT data.
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.
Equalise the axes of all subplots individually by setting the system limits in each dimension 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.
points_trace
(points[, size, color, opacity, ...])Static method for creating a Plotly trace of points.
show
([equal_axes])Show the Plotly figure, optionally setting equal axes limits.
timeseries_trace
(points[, size, color, ...])Static method for creating a list of 3 Plotly traces of timeseries.
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])Attributes
- create_figure(**kwargs)[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.
- Returns
- fig
Plotly
Figure
instance
A Plotly Figure instance, with any number of subplots (as defined when instantiating the class) pre-configured for PEPT data.
- fig
- property xlim#
- property ylim#
- property fig#
- static timeseries_trace(points, size=6.0, color=None, opacity=0.8, colorbar=True, colorbar_col=-1, colorscale='Magma', colorbar_title=None, **kwargs)[source]#
Static method for creating a list of 3 Plotly traces of timeseries. See PlotlyGrapher2D.add_timeseries for the full documentation.
- add_timeseries(points, rows_cols=[(1, 1), (2, 1), (3, 1)], size=6.0, color=None, opacity=0.8, colorbar=True, colorbar_col=-1, colorscale='Magma', colorbar_title=None, **kwargs)[source]#
Add a timeseries plot for each dimension in points vs. time.
If the current PlotlyGrapher2D figure does not have enough rows and columns to accommodate the three subplots (at coordinates rows_cols), the inner figure will be regenerated with enough rows and columns.
- Parameters
- points(
M
,N
>= 4)numpy.ndarray
orpept.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.
- rows_cols
list
[tuple
[2]] A list with 3 tuples, each tuple containing the subplot indices to plot the x, y, and z coordinates (indexed from 1).
- size
float
,default
6.0 The marker size of the points.
- color
str
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.
- opacity
float
,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_col
int
,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).
- colorscale
str
,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_title
str
, optional If set, the colorbar will have this title above it.
- points(
- 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 3D points (data columns: [time, x, y, z]) to a PlotlyGrapher2D instance:
>>> grapher = PlotlyGrapher2D() >>> points_raw = np.array(...) # shape (N, M >= 4) >>> grapher.add_timeseries(points_raw) >>> grapher.show()
Add all the points in a PointData instance:
>>> point_data = pept.PointData(...) # Some example data >>> grapher.add_timeseries(point_data) >>> grapher.show()
- 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 PlotlyGrapher2D.add_points for the full documentation.
- add_points(points, row=1, col=1, size=6.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, with possible color-coding.
Creates a plotly.graph_objects.Scatter object for all the points included in the numpy array points and adds it to the subplot selected by row and col.
The expected data columns are [time, x1, y1, …].
- Parameters
- points(
M
,N
>= 2)numpy.ndarray
Points to plot. The expected data columns are: [t, x1, y1, etc.].
- row
int
,default
1 The row of the subplot to add a trace to.
- col
int
,default
1 The column of the subplot to add a trace to.
- size
float
,default
2.0 The marker size of the points.
- color
str
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.
- opacity
float
,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_col
int
,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).
- colorscale
str
,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_title
str
, optional If set, the colorbar will have this title above it.
- points(
- Raises
ValueError
If points is not a numpy.ndarray with shape (M, N), where N >= 3.
Examples
Add an array of points (data columns: [time, x, y]) to a PlotlyGrapher2D instance:
>>> grapher = PlotlyGrapher2D() >>> points_raw = np.random.random((10, 3)) >>> grapher.add_points(points_raw) >>> 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 >= 3), N very large >>> grapher.add_points(pts[::10])
- static lines_trace(lines, width=2.0, color=None, opacity=0.6, **kwargs)[source]#
Static method for creating a Plotly trace of lines. See PlotlyGrapher2D.add_lines for the full documentation.
- add_lines(lines, row=1, col=1, width=2.0, color=None, opacity=0.6, **kwargs)[source]#
Create and plot a trace for all the lines in a numpy array, with possible color-coding.
Creates a plotly.graph_objects.Scatter object for all the lines included in the numpy array 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 [x1, y1, x2, y2, …].
- Parameters
- lines(
M
,N
>= 5)numpy.ndarray
The expected data columns are: [time, x1, y1, x2, y2, etc.].
- row
int
,default
1 The row of the subplot to add a trace to.
- col
int
,default
1 The column of the subplot to add a trace to.
- width
float
,default
2.0 The width of the lines.
- color
str
or list-like, optional Can be a single color (e.g. “black”, “rgb(122, 15, 241)”).
- opacity
float
,default
0.6 The opacity of the lines, where 0 is transparent and 1 is fully opaque.
- lines(
- Raises
ValueError
If lines is not a numpy.ndarray with shape (M, N), where N >= 5.
Examples
Add an array of lines (data columns: [time, x1, y1, x2, y2]) to a PlotlyGrapher instance:
>>> grapher = PlotlyGrapher2D() >>> lines_raw = np.random.random((100, 5)) >>> grapher.add_lines(lines_raw) >>> 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 >= 5), N very large >>> grapher.add_lines(lines_raw[::10])
- add_pixels(pixels, row=1, col=1, colorscale='Magma', transpose=True, xgap=0.0, ygap=0.0, **kwargs)[source]#
Create and plot a trace with all the pixels in this class, with possible filtering.
Creates a plotly.graph_objects.Heatmap 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
- pixels
pept.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.
- row
int
,default
1 The row of the subplot to add a trace to.
- col
int
,default
1 The column of the subplot to add a trace to.
- colorscale
str
,default
“Magma” The Plotly scheme for color-coding the pixel 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.
- transposebool,
default
True
Transpose the heatmap (i.e. flip it across its diagonal).
- pixels
Examples
Pixellise an array of lines and add them to a PlotlyGrapher instance:
>>> grapher = PlotlyGrapher2D() >>> 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_pixels(pixels) >>> grapher.show()
- add_image(image, **kwargs)[source]#
Create and plot a go.Image trace.
- Parameters
- image(
width
,height
, 3 or 4)np.ndarray
An image with 3 (RGB) or 4 (RGBA) channels.
- **kwargs
keyword
arguments
Other arguments to be passed to the plotly.graph_objs.Image constructor.
- image(
- 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.
- 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.
- 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.
- equalise_separate()[source]#
Equalise the axes of all subplots individually by setting the system limits in each dimension to equal values, such that all data plotted is within the plotted bounds.
- 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"
- to_html(filepath, equal_axes=True, include_plotlyjs=True)[source]#
Save the current Plotly figure as a self-contained HTML webpage.
- Parameters
- filepath
str
orwriteable
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_plotlyjs
True
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.
- filepath
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")