Skip to content

flixopt.plotting

Comprehensive visualization toolkit for flixopt optimization results and data analysis.

This module provides a unified plotting interface supporting both Plotly (interactive) and Matplotlib (static) backends for visualizing energy system optimization results. It offers specialized plotting functions for time series, heatmaps, network diagrams, and statistical analyses commonly needed in energy system modeling.

Key Features

Dual Backend Support: Seamless switching between Plotly and Matplotlib Energy System Focus: Specialized plots for power flows, storage states, emissions Color Management: Intelligent color processing and palette management Export Capabilities: High-quality export for reports and publications Integration Ready: Designed for use with CalculationResults and standalone analysis

Main Plot Types
  • Time Series: Flow rates, power profiles, storage states over time
  • Heatmaps: High-resolution temporal data visualization with customizable aggregation
  • Network Diagrams: System topology with flow visualization
  • Statistical Plots: Distribution analysis, correlation studies, performance metrics
  • Comparative Analysis: Multi-scenario and sensitivity study visualizations

The module integrates seamlessly with flixopt's result classes while remaining accessible for standalone data visualization tasks.

Attributes

ColorType module-attribute

Python
ColorType = str | list[str] | dict[str, str]

Flexible color specification type supporting multiple input formats for visualization.

Color specifications can take several forms to accommodate different use cases:

Named Colormaps (str): - Standard colormaps: 'viridis', 'plasma', 'cividis', 'tab10', 'Set1' - Energy-focused: 'portland' (custom flixopt colormap for energy systems) - Backend-specific maps available in Plotly and Matplotlib

Color Lists (list[str]): - Explicit color sequences: ['red', 'blue', 'green', 'orange'] - HEX codes: ['#FF0000', '#0000FF', '#00FF00', '#FFA500'] - Mixed formats: ['red', '#0000FF', 'green', 'orange']

Label-to-Color Mapping (dict[str, str]): - Explicit associations: {'Wind': 'skyblue', 'Solar': 'gold', 'Gas': 'brown'} - Ensures consistent colors across different plots and datasets - Ideal for energy system components with semantic meaning

Examples:

Python
# Named colormap
colors = 'viridis'  # Automatic color generation

# Explicit color list
colors = ['red', 'blue', 'green', '#FFD700']

# Component-specific mapping
colors = {
    'Wind_Turbine': 'skyblue',
    'Solar_Panel': 'gold',
    'Natural_Gas': 'brown',
    'Battery': 'green',
    'Electric_Load': 'darkred'
}
Color Format Support
  • Named Colors: 'red', 'blue', 'forestgreen', 'darkorange'
  • HEX Codes: '#FF0000', '#0000FF', '#228B22', '#FF8C00'
  • RGB Tuples: (255, 0, 0), (0, 0, 255) [Matplotlib only]
  • RGBA: 'rgba(255,0,0,0.8)' [Plotly only]
References
  • HTML Color Names: https://htmlcolorcodes.com/color-names/
  • Matplotlib Colormaps: https://matplotlib.org/stable/tutorials/colors/colormaps.html
  • Plotly Built-in Colorscales: https://plotly.com/python/builtin-colorscales/

PlottingEngine module-attribute

Python
PlottingEngine = Literal['plotly', 'matplotlib']

Identifier for the plotting engine to use.

Classes

ColorProcessor

Python
ColorProcessor(engine: PlottingEngine = 'plotly', default_colormap: str = 'viridis')

Intelligent color management system for consistent multi-backend visualization.

This class provides unified color processing across Plotly and Matplotlib backends, ensuring consistent visual appearance regardless of the plotting engine used. It handles color palette generation, named colormap translation, and intelligent color cycling for complex datasets with many categories.

Key Features

Backend Agnostic: Automatic color format conversion between engines Palette Management: Support for named colormaps, custom palettes, and color lists Intelligent Cycling: Smart color assignment for datasets with many categories Fallback Handling: Graceful degradation when requested colormaps are unavailable Energy System Colors: Built-in palettes optimized for energy system visualization

Color Input Types
  • Named Colormaps: 'viridis', 'plasma', 'portland', 'tab10', etc.
  • Color Lists: ['red', 'blue', 'green'] or ['#FF0000', '#0000FF', '#00FF00']
  • Label Dictionaries: {'Generator': 'red', 'Storage': 'blue', 'Load': 'green'}

Examples:

Basic color processing:

Python
# Initialize for Plotly backend
processor = ColorProcessor(engine='plotly', default_colormap='viridis')

# Process different color specifications
colors = processor.process_colors('plasma', ['Gen1', 'Gen2', 'Storage'])
colors = processor.process_colors(['red', 'blue', 'green'], ['A', 'B', 'C'])
colors = processor.process_colors({'Wind': 'skyblue', 'Solar': 'gold'}, ['Wind', 'Solar', 'Gas'])

# Switch to Matplotlib
processor = ColorProcessor(engine='matplotlib')
mpl_colors = processor.process_colors('tab10', component_labels)

Energy system visualization:

Python
# Specialized energy system palette
energy_colors = {
    'Natural_Gas': '#8B4513',  # Brown
    'Electricity': '#FFD700',  # Gold
    'Heat': '#FF4500',  # Red-orange
    'Cooling': '#87CEEB',  # Sky blue
    'Hydrogen': '#E6E6FA',  # Lavender
    'Battery': '#32CD32',  # Lime green
}

processor = ColorProcessor('plotly')
flow_colors = processor.process_colors(energy_colors, flow_labels)

Parameters:

Name Type Description Default
engine PlottingEngine

Plotting backend ('plotly' or 'matplotlib'). Determines output color format.

'plotly'
default_colormap str

Fallback colormap when requested palettes are unavailable. Common options: 'viridis', 'plasma', 'tab10', 'portland'.

'viridis'

Initialize the color processor with specified backend and defaults.

Functions

process_colors
Python
process_colors(colors: ColorType, labels: list[str], return_mapping: bool = False) -> list[Any] | dict[str, Any]

Process colors for the specified labels.

Parameters:

Name Type Description Default
colors ColorType

Color specification (colormap name, list of colors, or label-to-color mapping)

required
labels list[str]

list of data labels that need colors assigned

required
return_mapping bool

If True, returns a dictionary mapping labels to colors; if False, returns a list of colors in the same order as labels

False

Returns:

Type Description
list[Any] | dict[str, Any]

Either a list of colors or a dictionary mapping labels to colors

Functions

with_plotly

Python
with_plotly(data: DataFrame | DataArray | Dataset, mode: Literal['stacked_bar', 'line', 'area', 'grouped_bar'] = 'stacked_bar', colors: ColorType = 'viridis', title: str = '', ylabel: str = '', xlabel: str = 'Time in h', fig: Figure | None = None, facet_by: str | list[str] | None = None, animate_by: str | None = None, facet_cols: int = 3, shared_yaxes: bool = True, shared_xaxes: bool = True) -> go.Figure

Plot data with Plotly using facets (subplots) and/or animation for multidimensional data.

Uses Plotly Express for convenient faceting and animation with automatic styling. For simple plots without faceting, can optionally add to an existing figure.

Parameters:

Name Type Description Default
data DataFrame | DataArray | Dataset

A DataFrame or xarray DataArray/Dataset to plot.

required
mode Literal['stacked_bar', 'line', 'area', 'grouped_bar']

The plotting mode. Use 'stacked_bar' for stacked bar charts, 'line' for lines, 'area' for stacked area charts, or 'grouped_bar' for grouped bar charts.

'stacked_bar'
colors ColorType

Color specification (colormap, list, or dict mapping labels to colors).

'viridis'
title str

The main title of the plot.

''
ylabel str

The label for the y-axis.

''
xlabel str

The label for the x-axis.

'Time in h'
fig Figure | None

A Plotly figure object to plot on (only for simple plots without faceting). If not provided, a new figure will be created.

None
facet_by str | list[str] | None

Dimension(s) to create facets for. Creates a subplot grid. Can be a single dimension name or list of dimensions (max 2 for facet_row and facet_col). If the dimension doesn't exist in the data, it will be silently ignored.

None
animate_by str | None

Dimension to animate over. Creates animation frames. If the dimension doesn't exist in the data, it will be silently ignored.

None
facet_cols int

Number of columns in the facet grid (used when facet_by is single dimension).

3
shared_yaxes bool

Whether subplots share y-axes.

True
shared_xaxes bool

Whether subplots share x-axes.

True

Returns:

Type Description
Figure

A Plotly figure object containing the faceted/animated plot.

Examples:

Simple plot:

Python
fig = with_plotly(df, mode='area', title='Energy Mix')

Facet by scenario:

Python
fig = with_plotly(ds, facet_by='scenario', facet_cols=2)

Animate by period:

Python
fig = with_plotly(ds, animate_by='period')

Facet and animate:

Python
fig = with_plotly(ds, facet_by='scenario', animate_by='period')

with_matplotlib

Python
with_matplotlib(data: DataFrame, mode: Literal['stacked_bar', 'line'] = 'stacked_bar', colors: ColorType = 'viridis', title: str = '', ylabel: str = '', xlabel: str = 'Time in h', figsize: tuple[int, int] = (12, 6), fig: Figure | None = None, ax: Axes | None = None) -> tuple[plt.Figure, plt.Axes]

Plot a DataFrame with Matplotlib using stacked bars or stepped lines.

Parameters:

Name Type Description Default
data DataFrame

A DataFrame containing the data to plot. The index should represent time (e.g., hours), and each column represents a separate data series.

required
mode Literal['stacked_bar', 'line']

Plotting mode. Use 'stacked_bar' for stacked bar charts or 'line' for stepped lines.

'stacked_bar'
colors ColorType

Color specification, can be: - A string with a colormap name (e.g., 'viridis', 'plasma') - A list of color strings (e.g., ['#ff0000', '#00ff00']) - A dictionary mapping column names to colors (e.g., {'Column1': '#ff0000'})

'viridis'
title str

The title of the plot.

''
ylabel str

The ylabel of the plot.

''
xlabel str

The xlabel of the plot.

'Time in h'
figsize tuple[int, int]

Specify the size of the figure

(12, 6)
fig Figure | None

A Matplotlib figure object to plot on. If not provided, a new figure will be created.

None
ax Axes | None

A Matplotlib axes object to plot on. If not provided, a new axes will be created.

None

Returns:

Type Description
tuple[Figure, Axes]

A tuple containing the Matplotlib figure and axes objects used for the plot.

Notes
  • If mode is 'stacked_bar', bars are stacked for both positive and negative values. Negative values are stacked separately without extra labels in the legend.
  • If mode is 'line', stepped lines are drawn for each data series.

reshape_data_for_heatmap

Python
reshape_data_for_heatmap(data: DataArray, reshape_time: tuple[Literal['YS', 'MS', 'W', 'D', 'h', '15min', 'min'], Literal['W', 'D', 'h', '15min', 'min']] | Literal['auto'] | None = 'auto', facet_by: str | list[str] | None = None, animate_by: str | None = None, fill: Literal['ffill', 'bfill'] | None = 'ffill') -> xr.DataArray

Reshape data for heatmap visualization, handling time dimension intelligently.

This function decides whether to reshape the 'time' dimension based on the reshape_time parameter: - 'auto': Automatically reshapes if only 'time' dimension would remain for heatmap - Tuple: Explicitly reshapes time with specified parameters - None: No reshaping (returns data as-is)

All non-time dimensions are preserved during reshaping.

Parameters:

Name Type Description Default
data DataArray

DataArray to reshape for heatmap visualization.

required
reshape_time tuple[Literal['YS', 'MS', 'W', 'D', 'h', '15min', 'min'], Literal['W', 'D', 'h', '15min', 'min']] | Literal['auto'] | None

Reshaping configuration: - 'auto' (default): Auto-reshape if needed based on facet_by/animate_by - Tuple (timeframes, timesteps_per_frame): Explicit time reshaping - None: No reshaping

'auto'
facet_by str | list[str] | None

Dimension(s) used for faceting (used in 'auto' decision).

None
animate_by str | None

Dimension used for animation (used in 'auto' decision).

None
fill Literal['ffill', 'bfill'] | None

Method to fill missing values: 'ffill' or 'bfill'. Default is 'ffill'.

'ffill'

Returns:

Type Description
DataArray

Reshaped DataArray. If time reshaping is applied, 'time' dimension is replaced

DataArray

by 'timestep' and 'timeframe'. All other dimensions are preserved.

Examples:

Auto-reshaping:

Python
# Will auto-reshape because only 'time' remains after faceting/animation
data = reshape_data_for_heatmap(data, reshape_time='auto', facet_by='scenario', animate_by='period')

Explicit reshaping:

Python
# Explicitly reshape to daily pattern
data = reshape_data_for_heatmap(data, reshape_time=('D', 'h'))

No reshaping:

Python
# Keep data as-is
data = reshape_data_for_heatmap(data, reshape_time=None)

plot_network

Python
plot_network(node_infos: dict, edge_infos: dict, path: str | Path | None = None, controls: bool | list[Literal['nodes', 'edges', 'layout', 'interaction', 'manipulation', 'physics', 'selection', 'renderer']] = True, show: bool = False) -> pyvis.network.Network | None

Visualizes the network structure of a FlowSystem using PyVis, using info-dictionaries.

Parameters:

Name Type Description Default
path str | Path | None

Path to save the HTML visualization. False: Visualization is created but not saved. str or Path: Specifies file path (default: 'results/network.html').

None
controls bool | list[Literal['nodes', 'edges', 'layout', 'interaction', 'manipulation', 'physics', 'selection', 'renderer']]

UI controls to add to the visualization. True: Enables all available controls. list: Specify controls, e.g., ['nodes', 'layout']. Options: 'nodes', 'edges', 'layout', 'interaction', 'manipulation', 'physics', 'selection', 'renderer'. You can play with these and generate a Dictionary from it that can be applied to the network returned by this function. network.set_options() https://pyvis.readthedocs.io/en/latest/tutorial.html

True
show bool

Whether to open the visualization in the web browser. The calculation must be saved to show it. If no path is given, it defaults to 'network.html'.

False

Returns: The Network instance representing the visualization, or None if pyvis is not installed.

Notes: - This function requires pyvis. If not installed, the function prints a warning and returns None. - Nodes are styled based on type (e.g., circles for buses, boxes for components) and annotated with node information.

pie_with_plotly

Python
pie_with_plotly(data: DataFrame, colors: ColorType = 'viridis', title: str = '', legend_title: str = '', hole: float = 0.0, fig: Figure | None = None) -> go.Figure

Create a pie chart with Plotly to visualize the proportion of values in a DataFrame.

Parameters:

Name Type Description Default
data DataFrame

A DataFrame containing the data to plot. If multiple rows exist, they will be summed unless a specific index value is passed.

required
colors ColorType

Color specification, can be: - A string with a colorscale name (e.g., 'viridis', 'plasma') - A list of color strings (e.g., ['#ff0000', '#00ff00']) - A dictionary mapping column names to colors (e.g., {'Column1': '#ff0000'})

'viridis'
title str

The title of the plot.

''
legend_title str

The title for the legend.

''
hole float

Size of the hole in the center for creating a donut chart (0.0 to 1.0).

0.0
fig Figure | None

A Plotly figure object to plot on. If not provided, a new figure will be created.

None

Returns:

Type Description
Figure

A Plotly figure object containing the generated pie chart.

Notes
  • Negative values are not appropriate for pie charts and will be converted to absolute values with a warning.
  • If the data contains very small values (less than 1% of the total), they can be grouped into an "Other" category for better readability.
  • By default, the sum of all columns is used for the pie chart. For time series data, consider preprocessing.

pie_with_matplotlib

Python
pie_with_matplotlib(data: DataFrame, colors: ColorType = 'viridis', title: str = '', legend_title: str = 'Categories', hole: float = 0.0, figsize: tuple[int, int] = (10, 8), fig: Figure | None = None, ax: Axes | None = None) -> tuple[plt.Figure, plt.Axes]

Create a pie chart with Matplotlib to visualize the proportion of values in a DataFrame.

Parameters:

Name Type Description Default
data DataFrame

A DataFrame containing the data to plot. If multiple rows exist, they will be summed unless a specific index value is passed.

required
colors ColorType

Color specification, can be: - A string with a colormap name (e.g., 'viridis', 'plasma') - A list of color strings (e.g., ['#ff0000', '#00ff00']) - A dictionary mapping column names to colors (e.g., {'Column1': '#ff0000'})

'viridis'
title str

The title of the plot.

''
legend_title str

The title for the legend.

'Categories'
hole float

Size of the hole in the center for creating a donut chart (0.0 to 1.0).

0.0
figsize tuple[int, int]

The size of the figure (width, height) in inches.

(10, 8)
fig Figure | None

A Matplotlib figure object to plot on. If not provided, a new figure will be created.

None
ax Axes | None

A Matplotlib axes object to plot on. If not provided, a new axes will be created.

None

Returns:

Type Description
tuple[Figure, Axes]

A tuple containing the Matplotlib figure and axes objects used for the plot.

Notes
  • Negative values are not appropriate for pie charts and will be converted to absolute values with a warning.
  • If the data contains very small values (less than 1% of the total), they can be grouped into an "Other" category for better readability.
  • By default, the sum of all columns is used for the pie chart. For time series data, consider preprocessing.

dual_pie_with_plotly

Python
dual_pie_with_plotly(data_left: Series, data_right: Series, colors: ColorType = 'viridis', title: str = '', subtitles: tuple[str, str] = ('Left Chart', 'Right Chart'), legend_title: str = '', hole: float = 0.2, lower_percentage_group: float = 5.0, hover_template: str = '%{label}: %{value} (%{percent})', text_info: str = 'percent+label', text_position: str = 'inside') -> go.Figure

Create two pie charts side by side with Plotly, with consistent coloring across both charts.

Parameters:

Name Type Description Default
data_left Series

Series for the left pie chart.

required
data_right Series

Series for the right pie chart.

required
colors ColorType

Color specification, can be: - A string with a colorscale name (e.g., 'viridis', 'plasma') - A list of color strings (e.g., ['#ff0000', '#00ff00']) - A dictionary mapping category names to colors (e.g., {'Category1': '#ff0000'})

'viridis'
title str

The main title of the plot.

''
subtitles tuple[str, str]

Tuple containing the subtitles for (left, right) charts.

('Left Chart', 'Right Chart')
legend_title str

The title for the legend.

''
hole float

Size of the hole in the center for creating donut charts (0.0 to 1.0).

0.2
lower_percentage_group float

Group segments whose cumulative share is below this percentage (0–100) into "Other".

5.0
hover_template str

Template for hover text. Use %{label}, %{value}, %{percent}.

'%{label}: %{value} (%{percent})'
text_info str

What to show on pie segments: 'label', 'percent', 'value', 'label+percent', 'label+value', 'percent+value', 'label+percent+value', or 'none'.

'percent+label'
text_position str

Position of text: 'inside', 'outside', 'auto', or 'none'.

'inside'

Returns:

Type Description
Figure

A Plotly figure object containing the generated dual pie chart.

dual_pie_with_matplotlib

Python
dual_pie_with_matplotlib(data_left: Series, data_right: Series, colors: ColorType = 'viridis', title: str = '', subtitles: tuple[str, str] = ('Left Chart', 'Right Chart'), legend_title: str = '', hole: float = 0.2, lower_percentage_group: float = 5.0, figsize: tuple[int, int] = (14, 7), fig: Figure | None = None, axes: list[Axes] | None = None) -> tuple[plt.Figure, list[plt.Axes]]

Create two pie charts side by side with Matplotlib, with consistent coloring across both charts. Leverages the existing pie_with_matplotlib function.

Parameters:

Name Type Description Default
data_left Series

Series for the left pie chart.

required
data_right Series

Series for the right pie chart.

required
colors ColorType

Color specification, can be: - A string with a colormap name (e.g., 'viridis', 'plasma') - A list of color strings (e.g., ['#ff0000', '#00ff00']) - A dictionary mapping category names to colors (e.g., {'Category1': '#ff0000'})

'viridis'
title str

The main title of the plot.

''
subtitles tuple[str, str]

Tuple containing the subtitles for (left, right) charts.

('Left Chart', 'Right Chart')
legend_title str

The title for the legend.

''
hole float

Size of the hole in the center for creating donut charts (0.0 to 1.0).

0.2
lower_percentage_group float

Whether to group small segments (below percentage) into an "Other" category.

5.0
figsize tuple[int, int]

The size of the figure (width, height) in inches.

(14, 7)
fig Figure | None

A Matplotlib figure object to plot on. If not provided, a new figure will be created.

None
axes list[Axes] | None

A list of Matplotlib axes objects to plot on. If not provided, new axes will be created.

None

Returns:

Type Description
tuple[Figure, list[Axes]]

A tuple containing the Matplotlib figure and list of axes objects used for the plot.

heatmap_with_plotly

Python
heatmap_with_plotly(data: DataArray, colors: ColorType = 'viridis', title: str = '', facet_by: str | list[str] | None = None, animate_by: str | None = None, facet_cols: int = 3, reshape_time: tuple[Literal['YS', 'MS', 'W', 'D', 'h', '15min', 'min'], Literal['W', 'D', 'h', '15min', 'min']] | Literal['auto'] | None = 'auto', fill: Literal['ffill', 'bfill'] | None = 'ffill') -> go.Figure

Plot a heatmap visualization using Plotly's imshow with faceting and animation support.

This function creates heatmap visualizations from xarray DataArrays, supporting multi-dimensional data through faceting (subplots) and animation. It automatically handles dimension reduction and data reshaping for optimal heatmap display.

Automatic Time Reshaping

If only the 'time' dimension remains after faceting/animation (making the data 1D), the function automatically reshapes time into a 2D format using default values (timeframes='D', timesteps_per_frame='h'). This creates a daily pattern heatmap showing hours vs days.

Parameters:

Name Type Description Default
data DataArray

An xarray DataArray containing the data to visualize. Should have at least 2 dimensions, or a 'time' dimension that can be reshaped into 2D.

required
colors ColorType

Color specification (colormap name, list, or dict). Common options: 'viridis', 'plasma', 'RdBu', 'portland'.

'viridis'
title str

The main title of the heatmap.

''
facet_by str | list[str] | None

Dimension to create facets for. Creates a subplot grid. Can be a single dimension name or list (only first dimension used). Note: px.imshow only supports single-dimension faceting. If the dimension doesn't exist in the data, it will be silently ignored.

None
animate_by str | None

Dimension to animate over. Creates animation frames. If the dimension doesn't exist in the data, it will be silently ignored.

None
facet_cols int

Number of columns in the facet grid (used with facet_by).

3
reshape_time tuple[Literal['YS', 'MS', 'W', 'D', 'h', '15min', 'min'], Literal['W', 'D', 'h', '15min', 'min']] | Literal['auto'] | None

Time reshaping configuration: - 'auto' (default): Automatically applies ('D', 'h') if only 'time' dimension remains - Tuple like ('D', 'h'): Explicit time reshaping (days vs hours) - None: Disable time reshaping (will error if only 1D time data)

'auto'
fill Literal['ffill', 'bfill'] | None

Method to fill missing values when reshaping time: 'ffill' or 'bfill'. Default is 'ffill'.

'ffill'

Returns:

Type Description
Figure

A Plotly figure object containing the heatmap visualization.

Examples:

Simple heatmap:

Python
fig = heatmap_with_plotly(data_array, colors='RdBu', title='Temperature Map')

Facet by scenario:

Python
fig = heatmap_with_plotly(data_array, facet_by='scenario', facet_cols=2)

Animate by period:

Python
fig = heatmap_with_plotly(data_array, animate_by='period')

Automatic time reshaping (when only time dimension remains):

Python
# Data with dims ['time', 'scenario', 'period']
# After faceting and animation, only 'time' remains -> auto-reshapes to (timestep, timeframe)
fig = heatmap_with_plotly(data_array, facet_by='scenario', animate_by='period')

Explicit time reshaping:

Python
fig = heatmap_with_plotly(data_array, facet_by='scenario', animate_by='period', reshape_time=('W', 'D'))

heatmap_with_matplotlib

Python
heatmap_with_matplotlib(data: DataArray, colors: ColorType = 'viridis', title: str = '', figsize: tuple[float, float] = (12, 6), fig: Figure | None = None, ax: Axes | None = None, reshape_time: tuple[Literal['YS', 'MS', 'W', 'D', 'h', '15min', 'min'], Literal['W', 'D', 'h', '15min', 'min']] | Literal['auto'] | None = 'auto', fill: Literal['ffill', 'bfill'] | None = 'ffill') -> tuple[plt.Figure, plt.Axes]

Plot a heatmap visualization using Matplotlib's imshow.

This function creates a basic 2D heatmap from an xarray DataArray using matplotlib's imshow function. For multi-dimensional data, only the first two dimensions are used.

Parameters:

Name Type Description Default
data DataArray

An xarray DataArray containing the data to visualize. Should have at least 2 dimensions. If more than 2 dimensions exist, additional dimensions will be reduced by taking the first slice.

required
colors ColorType

Color specification. Should be a colormap name (e.g., 'viridis', 'RdBu').

'viridis'
title str

The title of the heatmap.

''
figsize tuple[float, float]

The size of the figure (width, height) in inches.

(12, 6)
fig Figure | None

A Matplotlib figure object to plot on. If not provided, a new figure will be created.

None
ax Axes | None

A Matplotlib axes object to plot on. If not provided, a new axes will be created.

None
reshape_time tuple[Literal['YS', 'MS', 'W', 'D', 'h', '15min', 'min'], Literal['W', 'D', 'h', '15min', 'min']] | Literal['auto'] | None

Time reshaping configuration: - 'auto' (default): Automatically applies ('D', 'h') if only 'time' dimension - Tuple like ('D', 'h'): Explicit time reshaping (days vs hours) - None: Disable time reshaping

'auto'
fill Literal['ffill', 'bfill'] | None

Method to fill missing values when reshaping time: 'ffill' or 'bfill'. Default is 'ffill'.

'ffill'

Returns:

Type Description
tuple[Figure, Axes]

A tuple containing the Matplotlib figure and axes objects used for the plot.

Notes
  • Matplotlib backend doesn't support faceting or animation. Use plotly engine for those features.
  • The y-axis is automatically inverted to display data with origin at top-left.
  • A colorbar is added to show the value scale.

Examples:

Python
fig, ax = heatmap_with_matplotlib(data_array, colors='RdBu', title='Temperature')
plt.savefig('heatmap.png')

Time reshaping:

Python
fig, ax = heatmap_with_matplotlib(data_array, reshape_time=('D', 'h'))

export_figure

Python
export_figure(figure_like: Figure | tuple[Figure, Axes], default_path: Path, default_filetype: str | None = None, user_path: Path | None = None, show: bool = True, save: bool = False) -> go.Figure | tuple[plt.Figure, plt.Axes]

Export a figure to a file and or show it.

Parameters:

Name Type Description Default
figure_like Figure | tuple[Figure, Axes]

The figure to export. Can be a Plotly figure or a tuple of Matplotlib figure and axes.

required
default_path Path

The default file path if no user filename is provided.

required
default_filetype str | None

The default filetype if the path doesnt end with a filetype.

None
user_path Path | None

An optional user-specified file path.

None
show bool

Whether to display the figure (default: True).

True
save bool

Whether to save the figure (default: False).

False

Raises:

Type Description
ValueError

If no default filetype is provided and the path doesn't specify a filetype.

TypeError

If the figure type is not supported.