interplot.arraytools: Array Tools

A collection of useful functions to work with numpy arrays.

interplot.arraytools.lowpass(data, n=101, new_index=None)

Moving average symetrically over n data points.

Accepts numpy arrays, lists and pandas Series.

Parameters:
data: array-like

np.array, list, tuple or pd.Series to filter.

n: int, optional

Number of data points to average over.

new_index: list-like, optional

If a pandas Series is provided as data, use this new_index.

Returns:
np.ndarray or pd.Series
interplot.arraytools.highpass(data, n=101, new_index=None)

Filter out low-frequency drift.

Offsets each datapoint by the average of the surrounding n data points. N must be odd.

Parameters:
data: array-like

np.array, list, tuple or pd.Series to filter.

n: int, optional

Number of data points to average over.

new_index: list-like, optional

If a pandas Series is provided as data, use this new_index.

Returns:
np.ndarray or pd.Series
interplot.arraytools.interp(array, pos)

Linearly interpolate between neighboring indexes.

Parameters:
array: 1D list-like
pos: float
Returns:
float

interpolated value

interplot.arraytools.downsample(max_length, *x, mode='step', axis=0)

Reduce size of array to max_length or lower.

If mode="step", each stepsize-th element is returned.

If mode="average", the array is averaged in bins of size stepsize.

If multiple x are provided, they are are assumed to have the same shape. stepsize is determined from the first element.

Parameters:
max_length: int
*x: np.ndarray

The array(s) to be downsampled. If multiple arrays are provided, the result will be a list of the downsampled arrays.

mode: str, default: step

Mode for downsampling to reduce file size.

Options:

  • step:

    Based on max_length and the array size, the smallest stepsize is determined, such that the new length is smaller or equal to max_length. Each stepsize-th element is displayed.

  • average:

    Bins of length stepsize are averaged. The remainders are discarded.

axis: int, default: 0

The axis along which to perform the downsampling.

interplot.arraytools.downsample_step(max_length, *x, axis=0)

Reduce size of array to max_length or lower by returning each stepsize-th element.

If multiple x are provided, they are are assumed to have the same shape. stepsize is determined from the first element.

Parameters:
max_length: int
*x: np.ndarray

The array(s) to be downsampled. If multiple arrays are provided, the result will be a list of the downsampled arrays.

axis: int, default: 0

The axis along which to perform the downsampling.

interplot.arraytools.downsample_average(max_length, *x, axis=0)

Reduce size of array to max_length or lower by returning each stepsize-th element.

If multiple x are provided, they are are assumed to have the same shape. stepsize is determined from the first element.

Parameters:
max_length: int
*x: np.ndarray

The array(s) to be downsampled. If multiple arrays are provided, the result will be a list of the downsampled arrays.

axis: int, default: 0

The axis along which to perform the downsampling.

class interplot.arraytools.LinearRegression(x, y, p=0.05, linspace=101)

Bases: NotebookInteraction

Model regression and its parameters.

Parameters:
x, y: array-like

Data points.

p: float, default: 0.05

p-value.

linspace: int, default: 101

Number of data points for linear regression model and conficence and prediction intervals.

Attributes:
The instance will provide the following data attributes:
x, y: array-like

The original data.

p: float

The original p-value.

poly: np.ndarray of 2x float

Polynomial coefficients. [a, b] -> a * x + b.

cov: float

Covariance matrix of the polynomial coefficient estimates. See for poly, cov: https://numpy.org/doc/stable/reference/generated/numpy.polyfit.html

y_model: np.ndarray

The regression modeled y values for the input x

n: int

Number of observations

m: int

Number of parameters

dof: int

Degree of freedoms n - m

t: float

t statistics

...

Methods

__call__(*args, **kwargs)

Calls the self.show() or self.plot() method.

plot(*[, fig, skip_post_process, ...])

Plot the correlation analysis.

JS_RENDER_WARNING = ''

Type:    str

plot(*, fig=None, skip_post_process=False, interactive=None, rows=1, cols=1, title=None, xlabel=None, ylabel=None, xlim=None, ylim=None, xlog=False, ylog=False, shared_xaxes=False, shared_yaxes=False, column_widths=None, row_heights=None, fig_size=None, dpi=None, legend_loc=None, legend_title=None, legend_togglegroup=None, color_cycle=None, save_fig=None, save_format=None, save_config=None, global_custom_func=None, mpl_custom_func=None, pty_custom_func=None, pty_update_layout=None, **kwargs)

Plot the correlation analysis.

Parameters:
plot_ci, plot_pi: bool, optional

Plot the confidence and prediction intervals. Default: True

label: str or interplot.Labelgroup, optional
label_data, label_reg, label_ci, label_pi: str or callable, optional

Trace labels.

color_data, color_reg, color_ci, color_pi: str, optional

Trace color. Can be hex, rgb(a) or any named color that is understood by matplotlib. Default: None In the default case, Plot will cycle through COLOR_CYCLE.

kwargs_data, kwargs_reg, kwargs_ci, kwargs_pi: dict, optional

Keyword arguments to pass to corresponding figure element.

**kwargs: optional

Keyword arguments to pass to each figure element.

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 n rows and m 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 a tuple for each column.

xlog, ylog: bool or bool tuple, default: False

Logarithmic scale for the axis.

Either one boolean for the entire axis or one for each row/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

Width, height in pixels.

Default behavior defined by conf.MPL_FIG_SIZE and conf.PTY_FIG_SIZE. Plotly allows None for responsive size adapting to viewport.

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.

legend_togglegroup: bool, default: False

PLOTLY ONLY.

Whether legend items with the same group will be toggled together when clicking on a legend item.

color_cycle: list, optional

Cycle through colors in the provided list.

If left None, the default color cycle conf.COLOR_CYCLE will be used.

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.

An iterable of multiple paths / filenames may be provided. In this case the save command will be repeated for each element.

save_format: str, default: None

Provide a format for the exported plot, if not declared in save_fig.

An iterable of multiple formats may be provided. In this case the save command will be repeated for each element.

save_config: dict, default: None

Plotly only.

Pass config options to plotly.graph_objects.Figure.write_html(config=save_config).

global_custom_func: function, default: None

Pass a function reference to further style the figures.

>>> def global_custom_func(fig):
...     # do your customisations
...     fig.add_text(0, 0, "watermark", color="gray")
...
...     # also include default function
...     conf.GLOBAL_CUSTOM_FUNC(fig)
...
... fig = interplot.Plot(
...     global_custom_func=global_custom_func
... )
... fig.add_line(x, y)
... fig.post_process()  # global_custom_func will be executed here
... fig.show()
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):
...     # do your customisations
...     fig.do_stuff()
...     ax[0, 0].do_more()
...
...     # also include default function
...     fig, ax = conf.MPL_CUSTOM_FUNC(fig, ax)
...
...     return fig, ax
...
... fig = interplot.Plot(
...     interactive=False,
...     mpl_custom_func=mpl_custom_func
... )
... fig.add_line(x, y)
... fig.post_process()  # mpl_custom_func will be executed here
... fig.show()
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):
...     # do your customisations
...     fig.do_stuff()
...
...     # also include default function
...     fig = conf.PTY_CUSTOM_FUNC(fig)
...
...     return fig
...
... fig = interplot.Plot(
...     interactive=True,
...     pty_custom_func=pty_custom_func
... )
... fig.add_line(x, y)
... fig.post_process()  # pty_custom_func will be executed here
... fig.show()
pty_update_layout: dict, default: None

PLOTLY ONLY.

Pass keyword arguments to plotly's plotly.graph_objects.Figure.update_layout(**pty_update_layout)

Default: None

Returns:
interplot.Plot instance