sattoolbox.plots package

Subpackages

Submodules

sattoolbox.plots.cyclers module

This module contains predefined property cycles. Additionally this module contains helper functions to create, combine and manipulate property cycles for plots.

class sattoolbox.plots.cyclers.Colors(*values)[source]

Bases: Enum

An enumeration class Colors that defines various color palettes. New color-palettes can be added by creating a new enum member with a tuple of color codes. New Enum Members should avoid enum-names that are actually colors themselves. Attributes (Enum members):

SAT (tuple): A color palette similar to Okabe and Ito but in a different order.

Suitable for color-blind-friendly plots. Colors: blue, pink, green, orange, black, light blue, yellow, and gold.

OKABEITO (tuple): The Okabe and Ito color palette, designed to be colorblind-friendly.

Colors: black, green, blue, light blue, yellow, gold, orange, and pink.

RGB (tuple): A basic RGB color palette with primary and secondary colors.

Colors: red, green, blue, yellow, magenta, and cyan.

OKABEITO = ('#000000', '#009e74', '#0071b2', '#56b3e9', '#f0e442', '#e69f00', '#d55e00', '#cc79a7')
RGB = ('#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF')
SAT = ('#0071b2', '#cc79a7', '#009e74', '#d55e00', '#000000', '#56b3e9', '#f0e442', '#e69f00')
class sattoolbox.plots.cyclers.Linestyles(*values)[source]

Bases: Enum

An enumeration class that defines various line styles for plotting. These styles can be used to customize the appearance of lines in plots. New Enum Members should avoid enum-names that are actually linestyles themselves. Attributes (Enum members):

SAT (tuple): A collection of line styles, including predefined styles such as ‘solid’,

‘dashed’, ‘dotted’, and ‘dashdot’, as well as custom patterns defined by tuples. The custom patterns are specified as (offset, (on_off_sequence)), where ‘offset’ is the starting point of the pattern, and ‘on_off_sequence’ defines the lengths of dashes and spaces. Examples include:

  • ‘loosely dotted’: (0, (1, 10))

  • ‘densely dashdotdotted’: (0, (3, 1, 1, 1, 1, 1))

These styles are inspired by the Matplotlib documentation: https://matplotlib.org/stable/gallery/lines_bars_and_markers/linestyles.html

MAIN (tuple): A simplified collection of commonly used line styles, including:
  • ‘solid’

  • ‘dashed’

  • ‘dotted’

  • ‘dashdot’

MAIN = ('solid', 'dashed', 'dotted', 'dashdot')
SAT = ('solid', 'dashed', 'dotted', 'dashdot', (0, (3, 5, 1, 5, 1, 5)), (0, (1, 10)), (0, (5, 10)), (0, (3, 1, 1, 1)), (0, (3, 10, 1, 10, 1, 10)), (0, (1, 1)), (5, (10, 3)), (0, (5, 1)), (0, (3, 10, 1, 10)), (0, (3, 1, 1, 1, 1, 1)))
class sattoolbox.plots.cyclers.Markers(*values)[source]

Bases: Enum

An enumeration representing different marker cyclers for plots. These markers can be used to customize the appearance of points in plots. New Enum Members should avoid enum-names that are actually markers themselves. Attributes (Enum members):

SAT (tuple): A tuple of marker styles typically used for satellite-related plots.

Includes markers such as ‘+’, ‘x’, ‘2’, ‘*’, ‘|’, ‘_’, ‘1’.

FILLED (tuple): A tuple of filled marker styles for plots.

Includes markers such as ‘o’, ‘X’, ‘s’, ‘v’, ‘p’, ‘<’, ‘h’, ‘>’.

OPEN (tuple): A tuple of open marker styles, similar to SAT.

Includes markers such as ‘+’, ‘x’, ‘2’, ‘*’, ‘|’, ‘_’, ‘1’.

FILLED = ('o', 's', 'v', 'X', 'p', '<', 'h', '>')
OPEN = ('+', 'x', '$*$', '2', '|', '_', '1')
SAT = ('+', 'x', '$*$', '2', '|', '_', '1')
sattoolbox.plots.cyclers.combine_cycle_props(method='lcm', **kwargs)[source]

Combine properties from a dictionary into a cycler object using a specified method.

This function ensures that cyclers have the same length for all properties and replaces empty strings (‘’) with ‘None’ for line styles to support matplotlib cycler validation.

Parameters:
  • method (str, optional) – The method to combine the cycles. Currently, only ‘lcm’ (least common multiple) is supported. Default is ‘lcm’.

  • **kwargs (dict) – Arbitrary keyword arguments representing cycler properties. Each property can be a single value (str, int, or float) or a list of values. If a single value is provided, it will be wrapped in a list. Invalid keyword arguments are raised by matplotlib’s validators.

Returns:

A cycler object combining the provided properties based on the specified method.

Return type:

matplotlib.cycler.Cycler

Notes

  • If ‘linestyle’ is provided as an empty string (‘’), it will be replaced with ‘None’ to ensure compatibility with matplotlib.

  • If ‘linestyle’ is a list, all empty strings in the list will be replaced with ‘None’.

  • The ‘lcm’ method calculates the least common multiple of the lengths of the provided property lists and expands each list to match the LCM length.

Examples

>>> combine_cycle_props(color=['red', 'blue', 'green'], linestyle=['-', '--'])
cycler({'color': ['red', 'blue', 'green', 'red', 'blue', 'green']},
       'linestyle': ['-', '--', '-', '--', '-', '--'])
sattoolbox.plots.cyclers.create_cycle(cycle_dict=None, n_lines=0, **kwargs)[source]

Creates a cycler object based on the provided cycle dictionary and additional properties.

This function adjusts the cycle dictionary to account for the number of lines already plotted and optionally updates it with additional properties provided in kwargs.

Parameters:
  • cycle_dict (dict, optional) – A dictionary representing the cycle properties. Keys are property names (e.g., ‘color’, ‘linestyle’), and values are lists of values to cycle through. Defaults to an empty dictionary. This will usually be coming from plt.rcParams[‘axes.prop_cycle’].by_key() or from the cycler used on the last axes object when plotting multiple axes.

  • n_lines (int, optional) – The number of lines already plotted. Used to adjust the cycle so that it continues from the correct position. Defaults to 0.

  • **kwargs – Additional properties to update the cycle dictionary. These properties will override existing ones in cycle_dict.

Returns:

A tuple containing: - cycler.Cycler

The resulting cycler object created from the modified cycle dictionary. This cycler can be used for plots. It is a ‘least common multiple’ of all passed properties.

  • dict

    The updated cycle dictionary after modifications.

  • dict

    Remaining keyword arguments that were not used in the cycle dictionary.

Return type:

tuple

sattoolbox.plots.cyclers.get_cycle_from_tuple(key, value)[source]

Retrieve a property value from predefined types based on the given key and value.

Parameters:
  • key (str) – The property type key, such as ‘color’, ‘linestyle’, or ‘marker’.

  • value (str) – The property value to be matched or transformed.

Returns:

The corresponding property value from the predefined types if the key and value are valid. If the key and value pair is not recognized, the input value is returned as-is.

Return type:

Any

Notes

  • If the value is ‘cycle’, it is transformed to ‘SAT’ (as the default style).

  • Attempt to match the value (case-insensitive) to an enum name in the property type.

  • If the value does not match any enum name, the original value is returned.

sattoolbox.plots.plots module

This module contains the Plotter class, which is designed for creating and managing plots based on data from pandas DataFrames. It provides functionalities to:

  • initialize with a DataFrame, which is used for plotting

  • plot data from the DataFrame (different types of plots)

  • store and manage the plots

class sattoolbox.plots.plots.Plotter(physical_quantities: DataFrame | None = None, plot_settings: dict | None = None, style_default: str | None = 'screen')[source]

Bases: object

A class for convenient plotting from pandas DataFrames with matplotlib.

The plot(kind=’…’) method allows for plotting any kind of plot supported by pandas.DataFrame.plot() and additional custom kinds (currently available: ‘multi_scatter’, ‘R2_scatter, ‘R2_hebin’). The method takes care of setting up the figure, axes, and styles, and allows for customization of the plot through keyword arguments.

The plot_subplots method allows to plot multiple subplots in a single figure.

SAT custom styles are available for different use cases (screen, presentation, paper). The styles all use the sat_base style and extend or ovveride from that. The base style mostly defines the default color cycle, and the setup of the axis and ticks. Presentation Styles: (Optimized size and fontsize (18) for presentations) - ‘presentation’: style for plots filling the whole width of the presentation slide. - ‘presentation_half’: style for plots filling half the width (2 plots or plot plus text) Paper style sheets:

  • Reduced font size: 10

  • Linewidth, Markersize and ticks-size reduced

  • Various Paper Styles:
    • Sizes: regular (1.5 col –> 5.5 inch), half –> 5.5 inch, full –> 7.4 inch (see Elsevier author guidelines)

    • Black&White Paper (bw_paper): Color (3 shades of grey/black) and Linestyle Cycle changed, Grid turned off

Screen Style:
  • Size fitted to be almost fullscreen on a Full HD Screen

  • Facecolor: White

  • Fontsize: 20

  • Both minor and Major Grid activated

Available styles are:
  • paper

  • paper_half

  • paper_full

  • bw_paper

  • bw_paper_half

  • bw_paper_full

  • screen

  • presentation

  • presentation_half

Attributes: physical_quantities (pd.DataFrame): DataFrame containing information about physical quantities. plot_kinds_pd (list): List of valid plot kinds from pandas. plot_kinds_custom (list): List of custom plot kinds defined in this class. kind_specifics (dict): Dictionary containing specifics for each plot kind. sat_styles (list): List of available SAT styles. style_default (str): Default style for the plots.

get_last_context()[source]

Get the last style context used for plotting.

Returns:

The last style context used for plotting.

Return type:

dict

kind_specifics = {'R2_hexbin': {'defaults': {'grid': False, 'gridsize': 50, 'legend': False, 'mincnt': np.float64(5e-324)}, 'xcols_check': {'message': 'xcols must be a string for R2_hexbin plot.', 'type': <class 'str'>}, 'ycols_check': {'message': 'ycols must be a string for R2_hexbin plot.', 'type': <class 'str'>}}, 'R2_scatter': {'defaults': {'legend': False}, 'xcols_check': {'message': "xcols must be a string for R2_scatter plot. To plot multiple ycols over multiple xcols use kind='R2_multi_scatter'", 'type': <class 'str'>}, 'ycols_check': {'message': "ycols must be a string for R2_scatter plot. To plot multiple ycols use kind='R2_multi_scatter'", 'type': <class 'str'>}}, 'area': {'uses_cycler': True, 'xcols_check': {'message': 'xcols must be None or a string for area plot.', 'type': (<class 'NoneType'>, <class 'str'>)}}, 'bar': {}, 'barh': {}, 'box': {'defaults': {'legend': False}, 'xcols_check': {'message': 'xcols must be None for box plot (do not specify)', 'type': <class 'NoneType'>}}, 'density': {'uses_cycler': True}, 'hexbin': {'defaults': {'grid': False, 'gridsize': 50, 'legend': False, 'mincnt': np.float64(5e-324)}, 'xcols_check': {'message': 'xcols must be a string for hexbin plot.', 'type': <class 'str'>}, 'ycols_check': {'message': 'ycols must be a string for hexbin plot.', 'type': <class 'str'>}}, 'hist': {'xcols_check': {'message': 'xcols must be None for histograms (do not specify)', 'type': <class 'NoneType'>}}, 'kde': {'uses_cycler': True}, 'line': {'uses_cycler': True}, 'multi_scatter': {'defaults': {'linestyle': '', 'marker': 'o'}, 'kind_to_plot': 'line', 'xcols_check': {'message': 'xcols must be a string or a list of strings for multi_scatter plot.', 'type': (<class 'str'>, <class 'list'>, <class 'tuple'>)}, 'ycols_check': {'message': 'ycols must be a string or a list of strings for multi_scatter plot.', 'type': (<class 'str'>, <class 'list'>, <class 'tuple'>)}}, 'pie': {'xcols_check': {'message': 'xcols must be None for pie plot (do not specify)', 'type': <class 'NoneType'>}, 'ycols_check': {'message': 'ycols must be a string for pie plot.', 'type': <class 'str'>}}, 'scatter': {'defaults': {'legend': False}, 'xcols_check': {'message': "xcols must be a string for scatter plot. To plot multiple ycols over multiple xcols use kind='multi_scatter'", 'type': <class 'str'>}, 'ycols_check': {'message': "ycols must be a string for scatter plot. To plot multiple ycols use kind='multi_scatter'", 'type': <class 'str'>}}}
plot(df: DataFrame, kind: str | None = 'line', xcols: str | List[str] | None = None, xlabel: str | None = None, ycols: str | List[str] | None = None, ylabel: str | None = None, ax: Axes | None = None, fig: Figure | None = None, style: str | None = None, **kwargs) tuple[Figure, Axes | tuple[Axes]][source]

Plot from a DataFrame using pandas DataFrame.plot(). This method adds some convenience features to the pandas plot method, such as handling of styles, titles, and legends. It is a general method for plotting and can be used for any kind of plot supported by pandas (see Plotter.plot_kinds_pd) plus some additional plot types (see Plotter.plot_kinds_custom).

Parameters:
  • df (pd.DataFrame) – DataFrame containing the data to plot.

  • kind (str, optional) – Type of plot to create. Check Plotter.plot_kinds_pd and Plotter.plot_kinds_custom for available plot types. Default is ‘line’.

  • xcols (str or list of str, optional) – List of the column(s) to use for the x-axis. If not provided, the index of the DataFrame will be used as x-values. If multiple ycols are provided, x_col must either be a list of the same lengths or a single column name that will be used for all ycols.

  • xlabel (str, optional) – Label for the x-axis. Default is None. If None, the label will be inferred from the xcols name(s).

  • ycols (str or list of str, optional) – Name of the column(s) to use for the y-axis. If not provided, all columns from the DataFrame will be plotted.

  • ylabel (str, optional) – Label for the y-axis. Default is None. If None, the label will be inferred from the ycols name(s).

  • ax (matplotlib.axes.Axes, optional) – The axes on which to plot. If not provided, a new figure and axes will be created.

  • fig (matplotlib.figure.Figure, optional) – The figure on which to plot. If not provided, a new figure will be created.

  • style (str, optional) – Style to use for the plot. If not provided, the default style of the Plotter instance will be used.

  • **kwargs (dict) – Additional keyword arguments to pass to the plot. All keyword arguments accepted by pandas.DataFrame.plot are accepted.

Returns:

  • fig (matplotlib.figure.Figure) – The figure on which has been plotted.

  • ax (matplotlib.axes.Axes or tuple of matplotlib.axes.Axes) – The axes (or tuple of axes, if secondary axis is used) on which has been plotted.

plot_subplots(df: DataFrame, plots: dict, layout: tuple | None = None, style: str | None = None, figsize: tuple | None = None, hspace: float | None = 0.05, wspace: float | None = 0.05, **kwargs: dict | None) tuple[Figure, ndarray][source]

Plot multiple subplots in a single figure.

Parameters:
  • df (pd.DataFrame) – DataFrame containing the data to plot.

  • plots (dict) – Dictionary where keys are subplot titles (showing the title can be supressed for each subplot with “title = None” within respective entry in the plots dict) and values are dicts containing keyword arguments for the plot (including plot kind). More information on available plot kinds and valid arguments can be obtained from the plot() method.

  • layout (tuple, optional) – Tuple containing the layout of the subplots (number of rows, number of columns). If not provided, the layout will be inferred from the number of plots.

  • style (str, optional) – Style to use for the plot. If not provided, the default style of the Plotter instance will be used.

  • figsize (tuple, optional) – Tuple containing the size of the figure (width, height) in inches. If not provided, the default size from the used style will be used.

  • hspace (float, optional) – Height space between the subplots as a fraction of size of the subplot group as a whole. If there are more than two rows, the hspace is shared between them. Default is 0.05. More information on padding: https://matplotlib.org/stable/users/explain/axes/constrainedlayout_guide.html#padding-and-spacing

  • wspace (float, optional) – Width space between the subplots as a fraction of size of the subplot group as a whole. If there are more than two columns, the wspace is shared between them. Default is 0.05. More information on padding: https://matplotlib.org/stable/users/explain/axes/constrainedlayout_guide.html#padding-and-spacing

  • **kwargs (optional) – Additional keyword arguments to pass to the subplot creation of matplotlib.pyplot.subplots(). For more information see: https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.subplots.html

Returns:

  • fig (matplotlib.figure.Figure) – The figure containing the subplots.

  • axs (numpy.ndarray of matplotlib.axes.Axes) – Array of axes objects representing the subplots.

sat_styles = ['screen', 'presentation', 'presentation_half', 'paper', 'paper_half', 'paper_full', 'bw_paper', 'bw_paper_half', 'bw_paper_full']
sattoolbox.plots.plots.create_legend(ax, loc='best', labels=None, **kwargs)[source]

Creates a (fancy) legend for the plot. This function is a wrapper around the matplotlib legend function. It removes the default legend(s) and creates a new one. Improvements over the matplotlib legend function are: - The location specifier ‘outside’ can be used to place the legend outside the plot area. - The direction of the plot entries is inferred (if not controlled via ncols). E.g. spreading

the entries horizontally if places above or below the plot.

  • Legend for two y axes is supported. Entries of both axis are put into the same legend. Subtitles for the two axes are supported (can be passed via ‘title’-kwarg as tuple of two strings). The entries of the two axis are spread over the columns of the legend.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes containing the plot.

  • loc (str, optional) – The location of the legend. Default is ‘best’.

  • labels (list, dict optional) – List of labels for the legend. If not provided, the labels of the plot will be used. If a dictionary is provided, the dictionary is used to update the existing labels. (Not implemented yet)

  • **kwargs (dict) – Additional keyword arguments to pass to the legend.

Returns:

leg – The legend object.

Return type:

matplotlib.legend.Legend

sattoolbox.plots.plots.example(example_types=['all'])[source]

Example usage of the Plotter class.

Parameters:

example_types (list, optional) – List of plot types to demonstrate. Default is [‘all’]. Possible values are: ‘all’, ‘style_examples’, ‘pd_kinds’, ‘multi_scatter’, ‘R2_plots’, ‘sec_axis’, ‘subplots’, ‘cycler’.

sattoolbox.plots.test_plots module

Module contents

Import Modules, that hold functions for the users of sattoolbox