plot module

Define helper functions for plots.

plot_susceptibility_with_grad(df, zcol, ax=None, xlim=None, ylim=None, ylabel=None, cmap=None, s=5, **kwargs)[source]

Draw lower and upper columns of df. Use zcol for color.

Parameters:
  • df (DataFrame) – Holds data to plot; must have columns with "lower" and "upper" in their name.

  • zcol (str) – Column in df used to colour the markers.

  • ax (Axes | None, default: None) – To re-use a pre-existing axis.

  • xlim (tuple[float, float] | None, default: None) – Plot limits.

  • ylim (tuple[float, float] | None, default: None) – Plot limits.

  • ylabel (str | None, default: None) – Label for y-axis.

  • cmap (Colormap | None, default: None) – Colour map to be used.

  • s (int, default: 5) – Size for the markers.

  • kwargs – Other keyword arguments passed to plt.scatter.

Return type:

Axes

plot_susceptibility_without_grad(df, label_to_color, ax=None, xlim=None, ylim=None, ylabel=None, s=5, **kwargs)[source]

Draw lower and upper columns of df.

Parameters:
Return type:

Axes

attribute_to_color(attributes)[source]

Map some attributes to colors.

Used for example by TestCampaign.check_somersalo_scaling_law(), to always keep the same plot color for a given frequency.

Parameters:

attributes (Iterable[TypeVar(T, bound= float)])

Return type:

dict[TypeVar(T, bound= float), tuple[float, float, float]]

plot_extrema_markers(ax_by_position, instruments, extrema, marker_style=None, zorder=3)[source]

Plot PowerExtremum values as markers from all instruments.

Todo

Fill above/below the extrema.

Parameters:
  • ax_by_position (dict[float, Axes] | Axes) – Axes (if same_figure=True) or dict mapping position to Axes.

  • instruments (list[Instrument]) – Instruments from which to extract values (must have .data and .position).

  • extrema (list[PowerExtremum]) – Global PowerExtremum instances (with .sample_index and .nature).

  • marker_style (dict[str, dict] | None, default: None) – Optional dict mapping nature (“minimum”, “maximum”) to plot kwargs (like color, marker shape, etc.).

  • zorder (int, default: 3) – Layer order.

Return type:

None

create_fig(title='', instruments_to_plot=(), xlabel=None, subplot_kw=None, **fig_kw)[source]

Create the figure and axes.

Parameters:
  • instruments_to_plot (Sequence[ABCMeta], default: ()) – Class of the instruments to be plotted.

  • fig_kw – Keyword arguments passsed to the Figure constructor.

  • title (str, default: '')

  • xlabel (str | None, default: None)

  • subplot_kw (dict | None, default: None)

Return type:

tuple[Figure, dict[ABCMeta, Axes]]

Returns:

Figure holding the axes.

Dictionary linking the class of the instruments to plot with the associated axes.

_create_axes(instruments_to_plot, fig, nrows, xlabel=None, **subplot_kw)[source]

Create the axes.

Parameters:
Return type:

dict[ABCMeta, Axes]

finish_fig(fig, axes, png_path=None)[source]

Save the figure, create the legend.

Parameters:
Return type:

tuple[Figure, list[Axes]]

create_df_to_plot(data_to_plot, head=None, tail=None, column_names='', drop_repeated_x=False, **kwargs)[source]

Merge the series into a single dataframe.

Parameters:
  • data_to_plot (Sequence[Series | DataFrame]) – List of the data that will be plotted.

  • head (int | None, default: None) – Plot only the first head rows.

  • tail (int | None, default: None) – Plot only the last tail rows.

  • column_names (str | list[str], default: '') – To override the default column names. This is used in particular with the method TestCampaign.sweet_plot() when all_on_same_plot=True.

  • drop_repeated_x (bool, default: False) – If True, remove consecutive rows with identical x values.

  • kwargs – Other keyword arguments.

Return type:

DataFrame

Returns:

Contains x and y data that will be plotted.

match_x_and_y_column_names(x_columns, y_columns)[source]

Match name of x columns with y columns, remove duplicate columns.

Parameters:
  • x_columns (list[str] | None) – Name of the instrument(s) used as x-axis.

  • y_columns (list[list[str]] | list[list[list[str]]]) – Name of the instruments for y-axis, sorted by subplot. It can be 3-level nested list, in particular when we separate data between increasing and decreasing power values.

Return type:

tuple[list[str] | str | None, list[list[str]] | list[str]]

Returns:

Name of the instrument(s) used as x-axis. Three possibilities:

  • If it is None, we plot again sample index.

  • If it is a single Instrument name, it will be used as x-data for every plot.

  • If it is a list of names, its length matches the length of y_columns. This is typically what happens when we plot an instrument vs another.

Name of the instruments for y-axis.

actual_plot(df_to_plot, x_columns, y_columns, axes, grid=True, sharex=True, color=None, **kwargs)[source]

Plot the data, adapting to what is given.

Parameters:
  • df_to_plot (DataFrame) – Containts all the data that will be plotted.

  • x_columns (list[str] | str | None) – Name of the column(s) used for x axis.

  • y_columns (list[list[str]] | list[str]) – Name of the column(s) for y plot. If list of list, each sublist is a subplot.

  • axes (list[Axes]) – Axes to plot on.

  • grid (bool, default: True) – If the grid should be plotted.

  • sharex (bool | None, default: True) – To let the different subplots share the same x-axis. It is set to None when we re-use already existing Axes.

  • color (dict[str, str] | None, default: None) – Dictionary linking column names in df_to_plot to HTML colors. Used to keep the same color between different instruments at the same PickUp.

  • kwargs – Other keyword arguments passed to the plot function.

Return type:

list[Axes]

Returns:

Plotted axes, or an array containing them.

set_labels(axes, *ydata, xdata=None, xlabel='', ylabel='', **kwargs)[source]

Set proper ylabel for every subplot.

Parameters:
  • axes (Collection[Axes] | Axes) – Axes.

  • *ydata (ABCMeta) – Class of the plotted instruments.

  • xdata (ABCMeta | None, default: None) – Class of the x-data instrument if applicable.

  • xlabel (str, default: '') – Label used for x axis. If not given, we take ylabel attribute from xdata.

  • ylabel (str | Iterable, default: '') – Labels that will be given for every subplot. If not given, we take the ylabel attribute of every plotted class.

  • kwargs – kwargs

Return type:

None

save_figure(axes, png_path, verbose=False, **png_kwargs)[source]

Save the figure.

Parameters:
  • axes (Axes | list[Axes]) – Holds one or several axes.

  • png_path (Path) – Where figure shall be saved.

  • verbose (bool, default: False) – To print a message indicating where Figure is saved.

  • **png_kwargs – Keyword arguments for the Figure.savefig method.

Return type:

None

save_dataframe(df_to_plot, csv_path, sep=',', verbose=False, **csv_kwargs)[source]

Save dataframe used to produce the plot.

Parameters:
  • df_to_plot (DataFrame) – DataFrame to save.

  • csv_path (Path) – Where to save DataFrame.

  • sep (str, default: ',') – Column delimiter.

  • verbose (bool, default: False) – To print a message indicating where Figure is saved.

  • csv_kwargs – Other keyword arguments for the DataFrame.to_csv method.

Return type:

None

add_background_color_according_to_power_growth(axe, growth_mask, grow_kw=None, decrease_kw=None, legend=True)[source]

Add a background color to indicate where power grows or not.

Parameters:
  • axe (Axes | Sequence[Axes] | ndarray[tuple[Any, ...], dtype[Axes]]) – The Axes on which to plot. If several are given, we sequentially call this function.

  • growth_mask (ndarray[tuple[Any, ...], dtype[bool]]) – A list containing True where power grows, False where decreases, np.nan when undetermined. Typical return value from ForwardPower.growth_mask().

  • grow_kw (dict | None, default: None) – How zones where power grows are colored. Default is a semi-transparent blue.

  • decrease_kw (dict | None, default: None) – How zones where power decreases are colored. Default is a semi-transparent red.

  • legend (bool, default: True) – If legend should be added.

Return type:

None

_add_single_bg_color(growth_mask, axe, label, invert_array, **color_kw)[source]

Add a single background color to the plot.

Parameters:
  • growth_mask (ndarray[tuple[Any, ...], dtype[bool]]) – Array where 1. means power grows, 0. means it decreases, np.nan is undetermined.

  • axe (Axes) – Where color should be plotted.

  • label (str | None) – The label of the background color.

  • invert_array (bool) – Should be False for grow plot, True for decrease plot. Serve as a filling value for nan.

  • color_kw (dict) – Keyword arguments given to axvspan.

Return type:

None

add_thresholds(threshold_set, axes=None, scale=1.0, alpha=0.5, legend=True, twinx=False, **kwargs)[source]

Add the thresholds position to a pre-existing plot.

Parameters:
Return type:

Axes | list[Axes]

plot_df_threshold(df, ylabel, label_to_color, fig_title, xticks, ms=8, lw=0.0, axes=None, plot_kwargs=None, **kwargs)[source]

Plot a threshold dataframe, separating lower/upper thresholds.

If no lower threshold is found, an error message is printed; we try to continue exectution anyway. If no upper threshold is found, there is no problem.

Parameters:
  • df (DataFrame) – Holds "{Instrument.name} lower" and "{Instrument.name} upper" columns.

  • ylabel (str) – Y label.

  • label_to_color (dict[str, tuple[float, float, float]]) – Maps threshold dataframe column names with a color.

  • fig_title (str) – Figure title.

  • xticks (Sequence[float]) – Position of xticks. A common choice is the position of power extrema.

  • ms (int, default: 8) – Markers size.

  • axes (Axes | None, default: None) – To re-use pre-existing axis.

  • plot_kwargs (dict[str, Any] | None, default: None) – Kwargs passed to the plotting function.

  • lw (float, default: 0.0)

Return type:

Axes

_merge_legends(ax1, ax2)[source]

Move the legend from ax1 to ax2.

Parameters:
Return type:

None

styles_from_column_cycle(columns, linestyles=None)[source]

Assign line styles to columns based on their suffixes for plotting.

Columns are expected to follow the naming convention produced by masking with suffixes, where each column name has the form "<base_name>__<suffix>". The part after the double underscore is used to distinguish the masked variants of the same base column.

Line styles are cycled through for each unique suffix across columns sharing the same base name.

Parameters:
  • columns (Iterable[str]) – The column names to assign styles to. Must follow the "<base_name>__<suffix>" convention.

  • linestyles (list[str] | None, default: None) – The list of line styles to cycle through (e.g., ['-', '--', ':', '-.']).

Return type:

dict[str, dict[str, str]]

Returns:

A dictionary mapping each column name to a dictionary with a "linestyle" key, e.g., {'col__a': {'linestyle': '-'}, 'col__b': {'linestyle': '--'}}.

default_ylabel()[source]

Produce a default y-label.

Return type:

str