toolbox.plot Documentation and API reference¶
Full API documentation of the toolbox.plot Python module.
Create matplotlib/plotly hybrid plots with a few lines of code.
It combines the best of the matplotlib and the plotly worlds through a unified, flat API. All the necessary boilerplate code is contained in this module.
Currently supported:
line plots (scatter)
line fills
histograms
heatmaps
boxplot
linear regression
text annotations
2D subplots
color cycling
Examples:
>>> toolbox.plot.line([0,4,6,7], [1,2,4,8])
>>> toolbox.plot.line(
... [0,4,6,7],
... [1,2,4,8],
... interactive=False,
... title="matploblib static figure",
... xlabel="X",
... ylabel="Y",
... )
>>> @tb.plot.magic_plot
... def plot_lines(samples=100, n=10, label="sigma={0}, mu={1}", fig=None):
... """
... Plot a line!
...
... Parameters
... ----------
... samples: int, optional
... Default 100
... n: int, optional
... Number of traces.
... Default: 10
... label: str, optional
... Trace label. May contain {0} for sigma and {1} for mu values.
... Default: "sigma={0}, mu={1}"
... [decorator parameters will be added automatically]
... """
... for i in range(1, n+1):
... fig.add_line(
... np.random.normal(i*10,i,samples), label=label.format(i, i*10))
>>> plot_lines(samples=200, title="Normally distributed Noise")
>>> plot_lines(
... samples=200, interactive=False, title="Normally distributed Noise")
The core Plot class¶
- class toolbox.plot.Plot(interactive=True, rows=1, cols=1, title=None, xlabel=None, ylabel=None, xlim=None, ylim=None, shared_xaxes=False, shared_yaxes=False, column_widths=None, row_heights=None, fig_size=None, dpi=100, legend_loc=None, legend_title=None, save_fig=None, save_format=None, save_config=None, pty_update_layout=None, pty_custom_func=None, mpl_custom_func=None)¶
Bases:
NotebookInteractionCreate matplotlib/plotly hybrid plots with a few lines of code.
It combines the best of the matplotlib and the plotly worlds through a unified, flat API. All the necessary boilerplate code is contained in this module.
Currently supported:
line plots (scatter)
line fills
histograms
heatmaps
boxplot
linear regression
text annotations
2D subplots
color cycling
- Parameters:
- interactive: bool, default: True
Display an interactive plotly line plot instead of the default matplotlib figure.
- rows, cols: int, default: 1
Create a grid with x rows and y columns.
- title: str, default: None
Plot title.
- xlabel, ylabel: str or str tuple, default: None
Axis labels.
Either one title for the entire axis or one for each row/column.
- xlim, ylim: tuple of 2 numbers or nested, default: None
Axis range limits.
- In case of multiple rows/cols provide either:
a tuple
a tuple for each row
a tuple for each row containing tuple for each column.
- shared_xaxes, shared_yaxes: str, default: None
Define how multiple subplots share there axes.
- Options:
“all” or True
“rows”
“columns” or “cols”
None or False
- column_widths, row_heights: tuple/list, default: None
Ratios of the width/height dimensions in each column/row. Will be normalised to a sum of 1.
- fig_size: tuple of 2x float, optional
Figure size in pixels.
- Default behavior:
MPL: Default figure size.
PLT: Responsive sizing.
- dpi: int, default: 100
Plot resolution.
- legend_loc: str, optional
MATPLOTLIB ONLY.
- Default:
In case of 1 line: None
In case of >1 line: “best” (auto-detect)
- legend_title: str, default: None
MPL: Each subplot has its own legend, so a 2d list in the shape of the subplots may be provided.
PTY: Just provide a str.
- save_fig: str or pathlib.Path, default: None
Provide a path to export the plot.
Possible formats: png, jpg, svg, html, …
The figure will only be saved on calling the instance’s .post_process().
If a directory (or True for local directory) is provided, the filename will be automatically generated based on the title.
- save_format: str, default: None
Provide a format for the exported plot.
- pty_update_layout: dict, default: None
PLOTLY ONLY. Pass keyword arguments to plotly’s fig.update_layout(**pty_update_layout) Thus, take full control over
- pty_custom_func: function, default: None
PLOTLY ONLY. Pass a function reference to further style the plotly graphs. Function must accept fig and return fig.
>>> def pty_custom_func(fig): ... fig.do_stuff() ... return fig
- mpl_custom_func: function, default: None
MATPLOTLIB ONLY. Pass a function reference to further style the matplotlib graphs. Function must accept fig, ax and return fig, ax.
Note: ax always has row and col coordinates, even if the plot is just 1x1.
>>> def mpl_custom_func(fig, ax): ... fig.do_stuff() ... ax[0, 0].do_more() ... return fig, ax
- Returns:
- toolbox.plot.Plot instance
Methods
__call__(*args, **kwargs)Calls the self.show() or self.plot() method.
add_boxplot(x[, horizontal, label, ...])Draw a boxplot.
add_fill(x, y1[, y2, label, show_legend, ...])Draw a fill between two y lines.
add_heatmap(data[, lim, aspect, invert_x, ...])Draw a heatmap.
add_hist([x, y, bins, density, label, ...])Draw a histogram.
add_line(x[, y, label, show_legend, color, ...])Draw a line plot.
add_regression(x[, y, p, linspace])Draw a linear regression plot.
add_text(x, y, text[, horizontal_alignment, ...])Draw text.
digest_color([color, alpha, increment])Parse color with matplotlib.colors to a rgba array.
get_cycle_color([increment, i])Retrieves the next color in the color cycle.
post_process([pty_update_layout, ...])Finish the plot.
save(path[, export_format, print_confirm])Save the plot.
show()Show the plot.
- JS_RENDER_WARNING = ''¶
- add_boxplot(x, horizontal=False, label=None, show_legend=None, color=None, color_median='black', opacity=None, notch=True, row=0, col=0, kwargs_pty=None, kwargs_mpl=None, **kwargs)¶
Draw a boxplot.
- Parameters:
- x: array or sequence of vectors
Data to build boxplot from.
- horizontal: bool, default: False
Show boxplot horizontally.
- label: tuple of strs, optional
Trace labels for legend.
- color: tuple of strs, optional
Fill colors.
Can be hex, rgb(a) or any named color that is understood by matplotlib.
Default: color is retrieved from Plot.digest_color, which cycles through COLOR_CYCLE.
- color_median: color, default: “black”
MPL only. Color of the median line.
- opacity: float, optional
Opacity (=alpha) of the fill.
By default, fallback to alpha value provided with color argument, or 1.
- row, col: int, optional
If the plot contains a grid, provide the coordinates.
Attention: Indexing starts with 0!
- kwargs_pty, kwargs_mpl, **kwargs: optional
Pass specific keyword arguments to the boxplot core method.
- add_fill(x, y1, y2=None, label=None, show_legend=False, mode='lines', color=None, opacity=0.5, line_width=0.0, line_opacity=1.0, line_color=None, row=0, col=0, kwargs_pty=None, kwargs_mpl=None, **kwargs)¶
Draw a fill between two y lines.
- Parameters:
- x: array-like
- y1, y2: array-like, optional
If only x and y1 is defined, it will be assumed as y1 and y2, and x will be the index, starting from 0.
- label: str, optional
Trace label for legend.
- color, line_color: str, optional
Fill and line color.
Can be hex, rgb(a) or any named color that is understood by matplotlib. If line_color is undefined, the the fill color will be used.
Default: color is retrieved from Plot.digest_color, which cycles through COLOR_CYCLE.
- opacity, line_opacity: float, default: 0.5
Opacity (=alpha) of the fill.
Set to None to use a value provided with the color argument.
- line_width: float, default: 0.
Boundary line width.
- row, col: int, default: 0
If the plot contains a grid, provide the coordinates.
Attention: Indexing starts with 0!
- kwargs_pty, kwargs_mpl, **kwargs: optional
Pass specific keyword arguments to the fill core method.
- add_heatmap(data, lim=(None, None), aspect=1, invert_x=False, invert_y=False, cmap='rainbow', cmap_under=None, cmap_over=None, cmap_bad=None, row=0, col=0, kwargs_pty=None, kwargs_mpl=None, **kwargs)¶
Draw a heatmap.
- Parameters:
- data: 2D array-like
2D data to show heatmap.
- lim: list/tuple of 2x float, optional
Lower and upper limits of the color map.
- aspect: float, default: 1
Aspect ratio of the axes.
- invert_x, invert_y: bool, optional
Invert the axes directions. Default: False
- cmap: str, default: “rainbow”
Color map to use. https://matplotlib.org/stable/gallery/color/colormap_reference.html Note: Not all cmaps are available for both libraries, and may differ slightly.
- cmap_under, cmap_over, cmap_bad: str, optional
Colors to display if under/over range or a pixel is invalid, e.g. in case of np.nan. cmap_bad is not available for interactive plotly plots.
- row, col: int, optional
If the plot contains a grid, provide the coordinates.
Attention: Indexing starts with 0!
- kwargs_pty, kwargs_mpl, **kwargs: optional
Pass specific keyword arguments to the heatmap core method.
- add_hist(x=None, y=None, bins=None, density=False, label=None, show_legend=None, color=None, opacity=None, row=0, col=0, kwargs_pty=None, kwargs_mpl=None, **kwargs)¶
Draw a histogram.
- Parameters:
- x: array-like
Histogram data.
- bins: int, optional
Number of bins. If undefined, plotly/matplotlib will detect automatically. Default: None
- label: str, optional
Trace label for legend.
- color: str, optional
Trace color. Can be hex, rgb(a) or any named color that is understood by matplotlib.
Default: color is retrieved from Plot.digest_color, which cycles through COLOR_CYCLE.
- opacity: float, optional
Opacity (=alpha) of the fill.
By default, fallback to alpha value provided with color argument, or 1.
- row, col: int, default: 0
If the plot contains a grid, provide the coordinates.
Attention: Indexing starts with 0!
- kwargs_pty, kwargs_mpl, **kwargs: optional
Pass specific keyword arguments to the hist core method.
- add_line(x, y=None, label=None, show_legend=None, color=None, opacity=None, linewidth=None, row=0, col=0, kwargs_pty=None, kwargs_mpl=None, **kwargs)¶
Draw a line plot.
- Parameters:
- x: array-like
- y: array-like, optional
If only x is defined, it will be assumed as y. If a pandas Series is provided, the index will be taken as x. Else if a pandas DataFrame is provided, the method call is looped for each column. Else x will be an increment, starting from 0. If a 2D numpy array is provided, the method call is looped for each column.
- label: str, optional
Trace label for legend.
- show_legend: bool, optional
Whether to show the label in the legend.
By default, it will be shown if a label is defined.
- color: str, optional
Trace color.
Can be hex, rgb(a) or any named color that is understood by matplotlib.
Default: color is retrieved from Plot.digest_color, which cycles through COLOR_CYCLE.
- opacity: float, optional
Opacity (=alpha) of the fill.
By default, fallback to alpha value provided with color argument, or 1.
- row, col: int, optional
If the plot contains a grid, provide the coordinates.
Attention: Indexing starts with 0!
- kwargs_pty, kwargs_mpl, **kwargs: optional
Pass specific keyword arguments to the line core method.
- add_regression(x, y=None, p=0.05, linspace=101, **kwargs)¶
Draw a linear regression plot.
- Parameters:
- x: array-like or `toolbox.arraytools.LinearRegression` instance
X axis data, or pre-existing LinearRegression instance.
- y: array-like, optional
Y axis data. If a LinearRegression instance is provided for x, y can be omitted and will be ignored.
- p: float, default: 0.05
p-value.
- linspace: int, default: 101
Number of data points for linear regression model and conficence and prediction intervals.
- kwargs:
Keyword arguments for toolbox.arraytools.LinearRegression.plot.
- add_text(x, y, text, horizontal_alignment='center', vertical_alignment='center', text_alignment=None, data_coords=None, x_data_coords=True, y_data_coords=True, color='black', opacity=None, row=0, col=0, kwargs_pty=None, kwargs_mpl=None, **kwargs)¶
Draw text.
- Parameters:
- x, y: float
Coordinates of the text.
- text: str
Text to add.
- horizontal_alignment, vertical_alignment: str, default: “center”
Where the coordinates of the text box anchor.
- Options for horizontal_alignment:
“left”
“center”
“right”
- Options for vertical_alignment:
“top”
“center”
“bottom”
- text_alignment: str, optional
Set how text is aligned inside its box.
If left undefined, horizontal_alignment will be used.
- data_coords: bool, default: True
Whether the x, y coordinates are provided in data coordinates or in relation to the axes.
If set to False, x, y should be in the range (0, 1). If data_coords is set, it will override x_data_coords and y_data_coords.
- x_data_coords, y_data_coords: bool, default: True
PTY only. Specify the anchor for each axis separate.
- color: str, default: “black”
Trace color. Can be hex, rgb(a) or any named color that is understood by matplotlib.
- opacity: float, optional
Opacity (=alpha) of the fill.
By default, fallback to alpha value provided with color argument, or 1.
- row, col: int, optional
If the plot contains a grid, provide the coordinates.
Attention: Indexing starts with 0!
- kwargs_pty, kwargs_mpl, **kwargs: optional
Pass specific keyword arguments to the line core method.
- digest_color(color=None, alpha=None, increment=1)¶
Parse color with matplotlib.colors to a rgba array.
- Parameters:
- color: any color format matplotlib accepts, optional
E.g. “blue”, “#0000ff” If None is provided, the next one from COLOR_CYCLE will be picked.
- alpha: float, optional
Set alpha / opacity. Overrides alpha contained in color input. Default: None (use the value contained in color or default to 1)
- increment: int, optional
If a color from the cycler is picked, increase the cycler by this increment.
- get_cycle_color(increment=1, i=None)¶
Retrieves the next color in the color cycle.
- Parameters:
- increment: int, optional
If the same color should be returned the next time, pass 0. To jump the next color, pass 2. Default: 1
- i: int, optional
Get a fixed index of the color cycle instead of the next one. This will not modify the regular color cycle iteration.
- Returns:
- color: str
HEX color, with leading hashtag
- post_process(pty_update_layout=None, pty_custom_func=None, mpl_custom_func=None)¶
Finish the plot.
- Parameters:
- Note: If not provided, the parameters given on init will be used.
- pty_update_layout: dict, optional
PLOTLY ONLY. Pass keyword arguments to plotly’s fig.update_layout(**pty_update_layout) Thus, take full control over Default: None
- pty_custom_func: function, optional
PLOTLY ONLY. Pass a function reference to further style the plotly graphs. Function must accept fig and return fig. Example: >>> def pty_custom_func(fig): >>> fig.do_stuff() >>> return fig Default: None
- mpl_custom_func: function, optional
MATPLOTLIB ONLY. Pass a function reference to further style the matplotlib graphs. Function must accept fig, ax and return fig, ax. Example: >>> def mpl_custom_func(fig, ax): >>> fig.do_stuff() >>> ax.do_more() >>> return fig, ax Default: None
- save(path, export_format=None, print_confirm=True, **kwargs)¶
Save the plot.
- Parameters:
- path: str, pathlib.Path, bool
May point to a directory or a filename. If only a directory is provided (or True for local directory), the filename will automatically be generated from the plot title.
- export_format: str, optional
If the format is not indicated in the file name, specify a format.
- print_confirm: bool, optional
Print a confirmation message where the file has been saved. Default: True
- Returns:
- pathlib.Path
Path to the exported file.
- show()¶
Show the plot.
One-line Plotting¶
- plot.line(*, interactive=True, rows=1, cols=1, fig=None, skip_post_process=False, title=None, xlabel=None, ylabel=None, xlim=None, ylim=None, shared_xaxes=False, shared_yaxes=False, column_widths=None, row_heights=None, fig_size=None, dpi=100, legend_loc=None, legend_title=None, save_fig=None, save_format=None, save_config=None, pty_update_layout=None, pty_custom_func=None, mpl_custom_func=None, **kwargs)¶
Draw a line plot.
- Parameters:
- x: array-like
- y: array-like, optional
If only x is defined, it will be assumed as y. If a pandas Series is provided, the index will be taken as x. Else if a pandas DataFrame is provided, the method call is looped for each column. Else x will be an increment, starting from 0. If a 2D numpy array is provided, the method call is looped for each column.
- label: str, optional
Trace label for legend.
- show_legend: bool, optional
Whether to show the label in the legend.
- interactive: bool, default: True
Display an interactive plotly line plot instead of the default matplotlib figure.
- rows, cols: int, default: 1
Create a grid with x rows and y columns.
- title: str, default: None
Plot title.
- xlabel, ylabel: str or str tuple, default: None
Axis labels.
Either one title for the entire axis or one for each row/column.
- xlim, ylim: tuple of 2 numbers or nested, default: None
Axis range limits.
- In case of multiple rows/cols provide either:
a tuple
a tuple for each row
a tuple for each row containing tuple for each column.
- shared_xaxes, shared_yaxes: str, default: None
Define how multiple subplots share there axes.
- Options:
“all” or True
“rows”
“columns” or “cols”
None or False
- column_widths, row_heights: tuple/list, default: None
Ratios of the width/height dimensions in each column/row. Will be normalised to a sum of 1.
- fig_size: tuple of 2x float, optional
Figure size in pixels.
- Default behavior:
MPL: Default figure size.
PLT: Responsive sizing.
- dpi: int, default: 100
Plot resolution.
- legend_loc: str, optional
MATPLOTLIB ONLY.
- Default:
In case of 1 line: None
In case of >1 line: “best” (auto-detect)
- legend_title: str, default: None
MPL: Each subplot has its own legend, so a 2d list in the shape of the subplots may be provided.
PTY: Just provide a str.
- save_fig: str or pathlib.Path, default: None
Provide a path to export the plot.
Possible formats: png, jpg, svg, html, …
The figure will only be saved on calling the instance’s .post_process().
If a directory (or True for local directory) is provided, the filename will be automatically generated based on the title.
- save_format: str, default: None
Provide a format for the exported plot.
- pty_update_layout: dict, default: None
PLOTLY ONLY. Pass keyword arguments to plotly’s fig.update_layout(**pty_update_layout) Thus, take full control over
- pty_custom_func: function, default: None
PLOTLY ONLY. Pass a function reference to further style the plotly graphs. Function must accept fig and return fig.
>>> def pty_custom_func(fig): ... fig.do_stuff() ... return fig
- mpl_custom_func: function, default: None
MATPLOTLIB ONLY. Pass a function reference to further style the matplotlib graphs. Function must accept fig, ax and return fig, ax.
Note: ax always has row and col coordinates, even if the plot is just 1x1.
>>> def mpl_custom_func(fig, ax): ... fig.do_stuff() ... ax[0, 0].do_more() ... return fig, ax
- Returns:
- toolbox.plot.Plot instance
By default, it will be shown if a label is defined.
- color: str, optional
Trace color.
Can be hex, rgb(a) or any named color that is understood by matplotlib.
Default: color is retrieved from Plot.digest_color, which cycles through COLOR_CYCLE.
- opacity: float, optional
Opacity (=alpha) of the fill.
By default, fallback to alpha value provided with color argument, or 1.
- row, col: int, optional
If the plot contains a grid, provide the coordinates.
Attention: Indexing starts with 0!
- kwargs_pty, kwargs_mpl, **kwargs: optional
Pass specific keyword arguments to the line core method.
- plot.hist(*, interactive=True, rows=1, cols=1, fig=None, skip_post_process=False, title=None, xlabel=None, ylabel=None, xlim=None, ylim=None, shared_xaxes=False, shared_yaxes=False, column_widths=None, row_heights=None, fig_size=None, dpi=100, legend_loc=None, legend_title=None, save_fig=None, save_format=None, save_config=None, pty_update_layout=None, pty_custom_func=None, mpl_custom_func=None, **kwargs)¶
Draw a histogram.
- Parameters:
- x: array-like
Histogram data.
- bins: int, optional
Number of bins. If undefined, plotly/matplotlib will detect automatically. Default: None
- label: str, optional
Trace label for legend.
- color: str, optional
Trace color. Can be hex, rgb(a) or any named color that is understood by matplotlib.
- interactive: bool, default: True
Display an interactive plotly line plot instead of the default matplotlib figure.
- rows, cols: int, default: 1
Create a grid with x rows and y columns.
- title: str, default: None
Plot title.
- xlabel, ylabel: str or str tuple, default: None
Axis labels.
Either one title for the entire axis or one for each row/column.
- xlim, ylim: tuple of 2 numbers or nested, default: None
Axis range limits.
- In case of multiple rows/cols provide either:
a tuple
a tuple for each row
a tuple for each row containing tuple for each column.
- shared_xaxes, shared_yaxes: str, default: None
Define how multiple subplots share there axes.
- Options:
“all” or True
“rows”
“columns” or “cols”
None or False
- column_widths, row_heights: tuple/list, default: None
Ratios of the width/height dimensions in each column/row. Will be normalised to a sum of 1.
- fig_size: tuple of 2x float, optional
Figure size in pixels.
- Default behavior:
MPL: Default figure size.
PLT: Responsive sizing.
- dpi: int, default: 100
Plot resolution.
- legend_loc: str, optional
MATPLOTLIB ONLY.
- Default:
In case of 1 line: None
In case of >1 line: “best” (auto-detect)
- legend_title: str, default: None
MPL: Each subplot has its own legend, so a 2d list in the shape of the subplots may be provided.
PTY: Just provide a str.
- save_fig: str or pathlib.Path, default: None
Provide a path to export the plot.
Possible formats: png, jpg, svg, html, …
The figure will only be saved on calling the instance’s .post_process().
If a directory (or True for local directory) is provided, the filename will be automatically generated based on the title.
- save_format: str, default: None
Provide a format for the exported plot.
- pty_update_layout: dict, default: None
PLOTLY ONLY. Pass keyword arguments to plotly’s fig.update_layout(**pty_update_layout) Thus, take full control over
- pty_custom_func: function, default: None
PLOTLY ONLY. Pass a function reference to further style the plotly graphs. Function must accept fig and return fig.
>>> def pty_custom_func(fig): ... fig.do_stuff() ... return fig
- mpl_custom_func: function, default: None
MATPLOTLIB ONLY. Pass a function reference to further style the matplotlib graphs. Function must accept fig, ax and return fig, ax.
Note: ax always has row and col coordinates, even if the plot is just 1x1.
>>> def mpl_custom_func(fig, ax): ... fig.do_stuff() ... ax[0, 0].do_more() ... return fig, ax
- Returns:
- toolbox.plot.Plot instance
Default: color is retrieved from Plot.digest_color, which cycles through COLOR_CYCLE.
- opacity: float, optional
Opacity (=alpha) of the fill.
By default, fallback to alpha value provided with color argument, or 1.
- row, col: int, default: 0
If the plot contains a grid, provide the coordinates.
Attention: Indexing starts with 0!
- kwargs_pty, kwargs_mpl, **kwargs: optional
Pass specific keyword arguments to the hist core method.
- plot.boxplot(*, interactive=True, rows=1, cols=1, fig=None, skip_post_process=False, title=None, xlabel=None, ylabel=None, xlim=None, ylim=None, shared_xaxes=False, shared_yaxes=False, column_widths=None, row_heights=None, fig_size=None, dpi=100, legend_loc=None, legend_title=None, save_fig=None, save_format=None, save_config=None, pty_update_layout=None, pty_custom_func=None, mpl_custom_func=None, **kwargs)¶
Draw a boxplot.
- Parameters:
- x: array or sequence of vectors
Data to build boxplot from.
- horizontal: bool, default: False
Show boxplot horizontally.
- label: tuple of strs, optional
Trace labels for legend.
- color: tuple of strs, optional
Fill colors.
- interactive: bool, default: True
Display an interactive plotly line plot instead of the default matplotlib figure.
- rows, cols: int, default: 1
Create a grid with x rows and y columns.
- title: str, default: None
Plot title.
- xlabel, ylabel: str or str tuple, default: None
Axis labels.
Either one title for the entire axis or one for each row/column.
- xlim, ylim: tuple of 2 numbers or nested, default: None
Axis range limits.
- In case of multiple rows/cols provide either:
a tuple
a tuple for each row
a tuple for each row containing tuple for each column.
- shared_xaxes, shared_yaxes: str, default: None
Define how multiple subplots share there axes.
- Options:
“all” or True
“rows”
“columns” or “cols”
None or False
- column_widths, row_heights: tuple/list, default: None
Ratios of the width/height dimensions in each column/row. Will be normalised to a sum of 1.
- fig_size: tuple of 2x float, optional
Figure size in pixels.
- Default behavior:
MPL: Default figure size.
PLT: Responsive sizing.
- dpi: int, default: 100
Plot resolution.
- legend_loc: str, optional
MATPLOTLIB ONLY.
- Default:
In case of 1 line: None
In case of >1 line: “best” (auto-detect)
- legend_title: str, default: None
MPL: Each subplot has its own legend, so a 2d list in the shape of the subplots may be provided.
PTY: Just provide a str.
- save_fig: str or pathlib.Path, default: None
Provide a path to export the plot.
Possible formats: png, jpg, svg, html, …
The figure will only be saved on calling the instance’s .post_process().
If a directory (or True for local directory) is provided, the filename will be automatically generated based on the title.
- save_format: str, default: None
Provide a format for the exported plot.
- pty_update_layout: dict, default: None
PLOTLY ONLY. Pass keyword arguments to plotly’s fig.update_layout(**pty_update_layout) Thus, take full control over
- pty_custom_func: function, default: None
PLOTLY ONLY. Pass a function reference to further style the plotly graphs. Function must accept fig and return fig.
>>> def pty_custom_func(fig): ... fig.do_stuff() ... return fig
- mpl_custom_func: function, default: None
MATPLOTLIB ONLY. Pass a function reference to further style the matplotlib graphs. Function must accept fig, ax and return fig, ax.
Note: ax always has row and col coordinates, even if the plot is just 1x1.
>>> def mpl_custom_func(fig, ax): ... fig.do_stuff() ... ax[0, 0].do_more() ... return fig, ax
- Returns:
- toolbox.plot.Plot instance
Can be hex, rgb(a) or any named color that is understood by matplotlib.
Default: color is retrieved from Plot.digest_color, which cycles through COLOR_CYCLE.
- color_median: color, default: “black”
MPL only. Color of the median line.
- opacity: float, optional
Opacity (=alpha) of the fill.
By default, fallback to alpha value provided with color argument, or 1.
- row, col: int, optional
If the plot contains a grid, provide the coordinates.
Attention: Indexing starts with 0!
- kwargs_pty, kwargs_mpl, **kwargs: optional
Pass specific keyword arguments to the boxplot core method.
- plot.heatmap(*, interactive=True, rows=1, cols=1, fig=None, skip_post_process=False, title=None, xlabel=None, ylabel=None, xlim=None, ylim=None, shared_xaxes=False, shared_yaxes=False, column_widths=None, row_heights=None, fig_size=None, dpi=100, legend_loc=None, legend_title=None, save_fig=None, save_format=None, save_config=None, pty_update_layout=None, pty_custom_func=None, mpl_custom_func=None, **kwargs)¶
Draw a heatmap.
- Parameters:
- data: 2D array-like
2D data to show heatmap.
- lim: list/tuple of 2x float, optional
Lower and upper limits of the color map.
- aspect: float, default: 1
Aspect ratio of the axes.
- invert_x, invert_y: bool, optional
Invert the axes directions. Default: False
- cmap: str, default: “rainbow”
Color map to use. https://matplotlib.org/stable/gallery/color/colormap_reference.html Note: Not all cmaps are available for both libraries, and may differ slightly.
- cmap_under, cmap_over, cmap_bad: str, optional
Colors to display if under/over range or a pixel is invalid, e.g. in case of np.nan. cmap_bad is not available for interactive plotly plots.
- row, col: int, optional
If the plot contains a grid, provide the coordinates.
- interactive: bool, default: True
Display an interactive plotly line plot instead of the default matplotlib figure.
- rows, cols: int, default: 1
Create a grid with x rows and y columns.
- title: str, default: None
Plot title.
- xlabel, ylabel: str or str tuple, default: None
Axis labels.
Either one title for the entire axis or one for each row/column.
- xlim, ylim: tuple of 2 numbers or nested, default: None
Axis range limits.
- In case of multiple rows/cols provide either:
a tuple
a tuple for each row
a tuple for each row containing tuple for each column.
- shared_xaxes, shared_yaxes: str, default: None
Define how multiple subplots share there axes.
- Options:
“all” or True
“rows”
“columns” or “cols”
None or False
- column_widths, row_heights: tuple/list, default: None
Ratios of the width/height dimensions in each column/row. Will be normalised to a sum of 1.
- fig_size: tuple of 2x float, optional
Figure size in pixels.
- Default behavior:
MPL: Default figure size.
PLT: Responsive sizing.
- dpi: int, default: 100
Plot resolution.
- legend_loc: str, optional
MATPLOTLIB ONLY.
- Default:
In case of 1 line: None
In case of >1 line: “best” (auto-detect)
- legend_title: str, default: None
MPL: Each subplot has its own legend, so a 2d list in the shape of the subplots may be provided.
PTY: Just provide a str.
- save_fig: str or pathlib.Path, default: None
Provide a path to export the plot.
Possible formats: png, jpg, svg, html, …
The figure will only be saved on calling the instance’s .post_process().
If a directory (or True for local directory) is provided, the filename will be automatically generated based on the title.
- save_format: str, default: None
Provide a format for the exported plot.
- pty_update_layout: dict, default: None
PLOTLY ONLY. Pass keyword arguments to plotly’s fig.update_layout(**pty_update_layout) Thus, take full control over
- pty_custom_func: function, default: None
PLOTLY ONLY. Pass a function reference to further style the plotly graphs. Function must accept fig and return fig.
>>> def pty_custom_func(fig): ... fig.do_stuff() ... return fig
- mpl_custom_func: function, default: None
MATPLOTLIB ONLY. Pass a function reference to further style the matplotlib graphs. Function must accept fig, ax and return fig, ax.
Note: ax always has row and col coordinates, even if the plot is just 1x1.
>>> def mpl_custom_func(fig, ax): ... fig.do_stuff() ... ax[0, 0].do_more() ... return fig, ax
- Returns:
- toolbox.plot.Plot instance
Attention: Indexing starts with 0!
- kwargs_pty, kwargs_mpl, **kwargs: optional
Pass specific keyword arguments to the heatmap core method.
- plot.regression(*, interactive=True, rows=1, cols=1, fig=None, skip_post_process=False, title=None, xlabel=None, ylabel=None, xlim=None, ylim=None, shared_xaxes=False, shared_yaxes=False, column_widths=None, row_heights=None, fig_size=None, dpi=100, legend_loc=None, legend_title=None, save_fig=None, save_format=None, save_config=None, pty_update_layout=None, pty_custom_func=None, mpl_custom_func=None, **kwargs)¶
Draw a linear regression plot.
- Parameters:
- x: array-like or `toolbox.arraytools.LinearRegression` instance
X axis data, or pre-existing LinearRegression instance.
- y: array-like, optional
Y axis data. If a LinearRegression instance is provided for x, y can be omitted and will be ignored.
- p: float, default: 0.05
p-value.
- linspace: int, default: 101
Number of data points for linear regression model and conficence and prediction intervals.
- kwargs:
Keyword arguments for toolbox.arraytools.LinearRegression.plot.
- interactive: bool, default: True
Display an interactive plotly line plot instead of the default matplotlib figure.
- rows, cols: int, default: 1
Create a grid with x rows and y columns.
- title: str, default: None
Plot title.
- xlabel, ylabel: str or str tuple, default: None
Axis labels.
Either one title for the entire axis or one for each row/column.
- xlim, ylim: tuple of 2 numbers or nested, default: None
Axis range limits.
- In case of multiple rows/cols provide either:
a tuple
a tuple for each row
a tuple for each row containing tuple for each column.
- shared_xaxes, shared_yaxes: str, default: None
Define how multiple subplots share there axes.
- Options:
“all” or True
“rows”
“columns” or “cols”
None or False
- column_widths, row_heights: tuple/list, default: None
Ratios of the width/height dimensions in each column/row. Will be normalised to a sum of 1.
- fig_size: tuple of 2x float, optional
Figure size in pixels.
- Default behavior:
MPL: Default figure size.
PLT: Responsive sizing.
- dpi: int, default: 100
Plot resolution.
- legend_loc: str, optional
MATPLOTLIB ONLY.
- Default:
In case of 1 line: None
In case of >1 line: “best” (auto-detect)
- legend_title: str, default: None
MPL: Each subplot has its own legend, so a 2d list in the shape of the subplots may be provided.
PTY: Just provide a str.
- save_fig: str or pathlib.Path, default: None
Provide a path to export the plot.
Possible formats: png, jpg, svg, html, …
The figure will only be saved on calling the instance’s .post_process().
If a directory (or True for local directory) is provided, the filename will be automatically generated based on the title.
- save_format: str, default: None
Provide a format for the exported plot.
- pty_update_layout: dict, default: None
PLOTLY ONLY. Pass keyword arguments to plotly’s fig.update_layout(**pty_update_layout) Thus, take full control over
- pty_custom_func: function, default: None
PLOTLY ONLY. Pass a function reference to further style the plotly graphs. Function must accept fig and return fig.
>>> def pty_custom_func(fig): ... fig.do_stuff() ... return fig
- mpl_custom_func: function, default: None
MATPLOTLIB ONLY. Pass a function reference to further style the matplotlib graphs. Function must accept fig, ax and return fig, ax.
Note: ax always has row and col coordinates, even if the plot is just 1x1.
>>> def mpl_custom_func(fig, ax): ... fig.do_stuff() ... ax[0, 0].do_more() ... return fig, ax
- Returns:
- toolbox.plot.Plot instance
- plot.fill(*, interactive=True, rows=1, cols=1, fig=None, skip_post_process=False, title=None, xlabel=None, ylabel=None, xlim=None, ylim=None, shared_xaxes=False, shared_yaxes=False, column_widths=None, row_heights=None, fig_size=None, dpi=100, legend_loc=None, legend_title=None, save_fig=None, save_format=None, save_config=None, pty_update_layout=None, pty_custom_func=None, mpl_custom_func=None, **kwargs)¶
Draw a fill between two y lines.
- Parameters:
- x: array-like
- y1, y2: array-like, optional
If only x and y1 is defined, it will be assumed as y1 and y2, and x will be the index, starting from 0.
- label: str, optional
Trace label for legend.
- color, line_color: str, optional
Fill and line color.
- interactive: bool, default: True
Display an interactive plotly line plot instead of the default matplotlib figure.
- rows, cols: int, default: 1
Create a grid with x rows and y columns.
- title: str, default: None
Plot title.
- xlabel, ylabel: str or str tuple, default: None
Axis labels.
Either one title for the entire axis or one for each row/column.
- xlim, ylim: tuple of 2 numbers or nested, default: None
Axis range limits.
- In case of multiple rows/cols provide either:
a tuple
a tuple for each row
a tuple for each row containing tuple for each column.
- shared_xaxes, shared_yaxes: str, default: None
Define how multiple subplots share there axes.
- Options:
“all” or True
“rows”
“columns” or “cols”
None or False
- column_widths, row_heights: tuple/list, default: None
Ratios of the width/height dimensions in each column/row. Will be normalised to a sum of 1.
- fig_size: tuple of 2x float, optional
Figure size in pixels.
- Default behavior:
MPL: Default figure size.
PLT: Responsive sizing.
- dpi: int, default: 100
Plot resolution.
- legend_loc: str, optional
MATPLOTLIB ONLY.
- Default:
In case of 1 line: None
In case of >1 line: “best” (auto-detect)
- legend_title: str, default: None
MPL: Each subplot has its own legend, so a 2d list in the shape of the subplots may be provided.
PTY: Just provide a str.
- save_fig: str or pathlib.Path, default: None
Provide a path to export the plot.
Possible formats: png, jpg, svg, html, …
The figure will only be saved on calling the instance’s .post_process().
If a directory (or True for local directory) is provided, the filename will be automatically generated based on the title.
- save_format: str, default: None
Provide a format for the exported plot.
- pty_update_layout: dict, default: None
PLOTLY ONLY. Pass keyword arguments to plotly’s fig.update_layout(**pty_update_layout) Thus, take full control over
- pty_custom_func: function, default: None
PLOTLY ONLY. Pass a function reference to further style the plotly graphs. Function must accept fig and return fig.
>>> def pty_custom_func(fig): ... fig.do_stuff() ... return fig
- mpl_custom_func: function, default: None
MATPLOTLIB ONLY. Pass a function reference to further style the matplotlib graphs. Function must accept fig, ax and return fig, ax.
Note: ax always has row and col coordinates, even if the plot is just 1x1.
>>> def mpl_custom_func(fig, ax): ... fig.do_stuff() ... ax[0, 0].do_more() ... return fig, ax
- Returns:
- toolbox.plot.Plot instance
Can be hex, rgb(a) or any named color that is understood by matplotlib. If line_color is undefined, the the fill color will be used.
Default: color is retrieved from Plot.digest_color, which cycles through COLOR_CYCLE.
- opacity, line_opacity: float, default: 0.5
Opacity (=alpha) of the fill.
Set to None to use a value provided with the color argument.
- line_width: float, default: 0.
Boundary line width.
- row, col: int, default: 0
If the plot contains a grid, provide the coordinates.
Attention: Indexing starts with 0!
- kwargs_pty, kwargs_mpl, **kwargs: optional
Pass specific keyword arguments to the fill core method.
- plot.text(*, interactive=True, rows=1, cols=1, fig=None, skip_post_process=False, title=None, xlabel=None, ylabel=None, xlim=None, ylim=None, shared_xaxes=False, shared_yaxes=False, column_widths=None, row_heights=None, fig_size=None, dpi=100, legend_loc=None, legend_title=None, save_fig=None, save_format=None, save_config=None, pty_update_layout=None, pty_custom_func=None, mpl_custom_func=None, **kwargs)¶
Draw text.
- Parameters:
- x, y: float
Coordinates of the text.
- text: str
Text to add.
- horizontal_alignment, vertical_alignment: str, default: “center”
Where the coordinates of the text box anchor.
- interactive: bool, default: True
Display an interactive plotly line plot instead of the default matplotlib figure.
- rows, cols: int, default: 1
Create a grid with x rows and y columns.
- title: str, default: None
Plot title.
- xlabel, ylabel: str or str tuple, default: None
Axis labels.
Either one title for the entire axis or one for each row/column.
- xlim, ylim: tuple of 2 numbers or nested, default: None
Axis range limits.
- In case of multiple rows/cols provide either:
a tuple
a tuple for each row
a tuple for each row containing tuple for each column.
- shared_xaxes, shared_yaxes: str, default: None
Define how multiple subplots share there axes.
- Options:
“all” or True
“rows”
“columns” or “cols”
None or False
- column_widths, row_heights: tuple/list, default: None
Ratios of the width/height dimensions in each column/row. Will be normalised to a sum of 1.
- fig_size: tuple of 2x float, optional
Figure size in pixels.
- Default behavior:
MPL: Default figure size.
PLT: Responsive sizing.
- dpi: int, default: 100
Plot resolution.
- legend_loc: str, optional
MATPLOTLIB ONLY.
- Default:
In case of 1 line: None
In case of >1 line: “best” (auto-detect)
- legend_title: str, default: None
MPL: Each subplot has its own legend, so a 2d list in the shape of the subplots may be provided.
PTY: Just provide a str.
- save_fig: str or pathlib.Path, default: None
Provide a path to export the plot.
Possible formats: png, jpg, svg, html, …
The figure will only be saved on calling the instance’s .post_process().
If a directory (or True for local directory) is provided, the filename will be automatically generated based on the title.
- save_format: str, default: None
Provide a format for the exported plot.
- pty_update_layout: dict, default: None
PLOTLY ONLY. Pass keyword arguments to plotly’s fig.update_layout(**pty_update_layout) Thus, take full control over
- pty_custom_func: function, default: None
PLOTLY ONLY. Pass a function reference to further style the plotly graphs. Function must accept fig and return fig.
>>> def pty_custom_func(fig): ... fig.do_stuff() ... return fig
- mpl_custom_func: function, default: None
MATPLOTLIB ONLY. Pass a function reference to further style the matplotlib graphs. Function must accept fig, ax and return fig, ax.
Note: ax always has row and col coordinates, even if the plot is just 1x1.
>>> def mpl_custom_func(fig, ax): ... fig.do_stuff() ... ax[0, 0].do_more() ... return fig, ax
- Returns:
- toolbox.plot.Plot instance
- Options for horizontal_alignment:
“left”
“center”
“right”
- Options for vertical_alignment:
“top”
“center”
“bottom”
- text_alignment: str, optional
Set how text is aligned inside its box.
If left undefined, horizontal_alignment will be used.
- data_coords: bool, default: True
Whether the x, y coordinates are provided in data coordinates or in relation to the axes.
If set to False, x, y should be in the range (0, 1). If data_coords is set, it will override x_data_coords and y_data_coords.
- x_data_coords, y_data_coords: bool, default: True
PTY only. Specify the anchor for each axis separate.
- color: str, default: “black”
Trace color. Can be hex, rgb(a) or any named color that is understood by matplotlib.
- opacity: float, optional
Opacity (=alpha) of the fill.
By default, fallback to alpha value provided with color argument, or 1.
- row, col: int, optional
If the plot contains a grid, provide the coordinates.
Attention: Indexing starts with 0!
- kwargs_pty, kwargs_mpl, **kwargs: optional
Pass specific keyword arguments to the line core method.
magic_plot decorators¶
- plot.magic_plot(doc_decorator=None)¶
Plot generator wrapper.
Your function feeds the data, the wrapper gives control over the plot to the user.
- Parameters:
- doc_decorator: str, optional
Append the docstring with the decorated parameters.
By default, the global variable DOCSTRING_DECORATOR will be used.
Examples
>>> @magic_plot ... def line( ... data, ... fig, ... **kwargs, ... ): ... fig.add_line(data) ... ... line([0,4,6,7], title="Plot title", interactive=False) [matplotlib figure, "Plot title"]
- plot.magic_plot_preset(**kwargs_preset)¶
Plot generator wrapper, preconfigured.
Your function feeds the data, the wrapper gives control over the plot to the user.
- Parameters:
- doc_decorator: str, optional
Append the docstring with the decorated parameters.
By default, the global variable DOCSTRING_DECORATOR will be used.
- **kwargs_preset: dict
Define presets for any keyword arguments accepted by Plot.
Setting strict_preset=True prevents overriding the preset.
Examples
>>> @magic_plot_preset( ... title="Data view", ... interactive=False, ... strict_preset=False, ... ) ... def line( ... data, ... fig, ... **kwargs, ... ): ... fig.add_line(data) ... ... line([0,4,6,7], xlabel="X axis") [matplotlib figure, "Data view"]
NotebookInteraction Parent Class¶
ShowDataArray, ShowDataset¶
- class toolbox.plot.ShowDataArray(data, default_sel=None, default_isel=None)¶
Bases:
NotebookInteractionAutomatically display a xarray.DataArray in a Jupyter notebook.
If the DataArray has more than two dimensions, provide default sel or isel selectors to reduce to two dimensions.
- Parameters:
- data: xarray.DataArray
- default_sel: dict, optional
Select a subset of a the DataArray by label. Can be a slice or the type of the dimension.
- default_isel: dict, optional
Select a subset of a the DataArray by integer count. Can be a integer slice or an integer.
Methods
__call__(*args, **kwargs)Calls the self.show() or self.plot() method.
plot(*args[, sel, isel])Show the DataArray.
- JS_RENDER_WARNING = ''¶
- plot(*args, sel=None, isel=None, **kwargs)¶
Show the DataArray.
- Parameters:
- sel: dict, optional
Select a subset of a the DataArray by label. Can be a slice or the type of the dimension. If None, default_sel will be used.
- isel: dict, optional
Select a subset of a the DataArray by integer count. Can be a integer slice or an integer. If None, default_isel will be used.
- Returns:
- Plot.fig
- class toolbox.plot.ShowDataset(data, default_var=None, default_sel=None, default_isel=None)¶
Bases:
ShowDataArrayAutomatically display a xarray.Dataset in a Jupyter notebook.
Provide a default variable to display from the Dataset for automatic display. If the Dataset has more than two dimensions, provide default sel or isel selectors to reduce to two dimensions.
- Parameters:
- data: xarray.DataArray
- default_var: str, optional
Select the variable of the Dataset to display by label.
- default_sel: dict, optional
Select a subset of a the Dataset by label. Can be a slice or the type of the dimension.
- default_isel: dict, optional
Select a subset of a the Dataset by integer count. Can be a integer slice or an integer.
Methods
__call__(*args, **kwargs)Calls the self.show() or self.plot() method.
plot(*args[, var, sel, isel])Show a variable of the Dataset.
- JS_RENDER_WARNING = ''¶
- plot(*args, var=None, sel=None, isel=None, **kwargs)¶
Show a variable of the Dataset.
- Parameters:
- var: str, optional
Select the variable of the Dataset to display by label. If None, default_var will be used.
- sel: dict, optional
Select a subset of a the DataArray by label. Can be a slice or the type of the dimension. If None, default_sel will be used.
- isel: dict, optional
Select a subset of a the DataArray by integer count. Can be a integer slice or an integer. If None, default_isel will be used.
- Returns:
- Plot.fig