Plots Module

The plots module provides comprehensive visualization tools for electrophysiological data analysis and publication-quality figure generation.

Module Overview

This module includes: * Histogram and distribution plotting functions * Cumulative probability visualizations * Model result plotting utilities * Probe layout and channel visualization * Feature distribution plotting across channel space

Core Functions

Basic Plotting Functions

Electrophysiological plotting and visualization module.

This module provides comprehensive plotting and visualization tools for electrophysiological data analysis, including feature distributions, probe visualizations, brain region mappings, and statistical plots.

The module includes: - Histogram plotting with quantile-based coloring - Cumulative probability plots for brain regions - Probe visualization in physical space - Feature distribution analysis - Brain region mapping and visualization - Statistical plotting utilities

Functions

plot_histogram

Create histograms with quantile-based color coding

plot_cumulative_probas

Plot cumulative probabilities of brain regions along probe depths

plot_results

Visualize model prediction results and feature distributions

select_series

Select data series based on features and brain region criteria

get_color_feat

Generate colors for feature values using colormaps

get_color_br

Generate colors for brain regions

plot_probe_rect

Plot probe channels as rectangles with specified colors

plot_probe_rect2

Plot probe channels using imshow for better visualization

figure_features_channel_space

Create comprehensive probe visualization with features and brain regions

plot_features_distributions

Create grid of histograms for feature distributions

Constants

QUANTILESlist

Default quantile values for histogram coloring

BINSint

Default number of bins for histograms

Examples

>>> from ephysatlas.plots import plot_histogram, plot_probe_rect2
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>>
>>> # Create sample data
>>> data = np.random.randn(1000)
>>>
>>> # Plot histogram
>>> plot_histogram(data, xlabel="Value", title="Sample Distribution")
>>>
>>> # Plot probe visualization
>>> xy = np.column_stack([np.arange(64), np.zeros(64)])
>>> colors = np.random.rand(64, 3)
>>> fig, ax = plt.subplots()
>>> plot_probe_rect2(xy, colors, ax)

Notes

This module integrates with the IBL (International Brain Laboratory) ecosystem and uses their styling conventions and brain region atlases. It provides both simple plotting functions and complex multi-panel visualizations for electrophysiological data analysis.

See Also

ephysatlas.features : Feature extraction and processing iblatlas.atlas : Brain region atlas functionality brainbox.ephys_plots : Additional electrophysiology plotting tools

ephysatlas.plots.plot_histogram(series, ax=None, quantiles=None, bins=None, xlabel=None, title=None, normalise=False)[source]

Create histograms with quantile-based color coding.

This function creates histograms with color coding based on quantile values, providing visual distinction between different ranges of the data distribution.

Parameters:
  • series (pd.Series or np.ndarray) – Data series to plot as histogram.

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

  • quantiles (list, optional) – Quantile values for color coding. Defaults to QUANTILES constant [0.01, 0.1, 0.9, 0.99].

  • bins (int, optional) – Number of histogram bins. Defaults to BINS constant (50).

  • xlabel (str, optional) – Label for the x-axis.

  • title (str, optional) – Title for the plot.

  • normalise (bool, optional) – Whether to normalize the histogram counts. Defaults to False.

Returns:

The function modifies the provided axes or creates a new plot.

Return type:

None

Note

The function uses the viridis colormap for quantile-based coloring. Sample count is displayed in the top-right corner of the plot.

ephysatlas.plots.plot_cumulative_probas(probas, depths, aids, regions=None, ax=None, legend=False)[source]

Plot cumulative probabilities of brain regions along probe depths.

Creates a stacked area plot showing the probability distribution of different brain regions at each depth along a probe trajectory. Each region is colored according to its standard atlas color.

Parameters:
  • probas (np.ndarray) – Array of shape (ndepths, nregions) containing probabilities for each region at each depth. Values should sum to 1 across regions for each depth.

  • depths (np.ndarray) – Vector of length ndepths containing the depth values along the probe trajectory.

  • aids (np.ndarray) – Vector of length nregions containing the atlas IDs for each region.

  • regions (iblatlas.BrainRegions, optional) – BrainRegions object containing region information. If None, a new instance is created.

  • ax (matplotlib.axes.Axes, optional) – Axes on which to plot. If None, the current axes will be used.

  • legend (bool, optional) – Whether to display a legend with region names. Defaults to False.

Returns:

The axes object containing the plot.

Return type:

matplotlib.axes.Axes

Note

The function creates a stacked area plot where each brain region is represented by a different color from the atlas. The y-axis represents depth along the probe.

ephysatlas.plots.plot_results(df, predicted_probas, dict_model, regions=None)[source]

Visualize model prediction results and feature distributions.

This function creates a comprehensive visualization of model prediction results, including feature heatmaps, cumulative probability plots for different folds, and entropy analysis across channels.

Parameters:
  • df (pd.DataFrame) – DataFrame containing channel data and features.

  • predicted_probas (np.ndarray) – Array of predicted probabilities with shape (n_folds, n_channels, n_classes) or (n_channels, n_classes).

  • dict_model (dict) – Model dictionary containing metadata including features and class information.

  • regions (iblatlas.BrainRegions, optional) – BrainRegions object for region visualization. If None, a new instance is created.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing all plots.

  • axs (np.ndarray): Array of matplotlib axes objects.

Return type:

tuple

Note

The function creates a multi-panel figure with feature heatmaps, probability plots for each fold, and entropy analysis. It automatically handles both single-fold and multi-fold prediction arrays.

ephysatlas.plots.select_series(df, features=None, acronym=None, id=None, mapping='Allen')[source]

Select data series based on features and brain region criteria.

This function filters a DataFrame to select specific features based on brain region criteria (acronym or ID) and returns the selected data series.

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

  • features (list, optional) – List of feature names to select. If None, uses all available voltage features. Defaults to None.

  • acronym (str, optional) – Brain region acronym to filter by. Mutually exclusive with id parameter.

  • id (int, optional) – Brain region ID to filter by. Mutually exclusive with acronym parameter.

  • mapping (str, optional) – Brain region mapping system to use. Defaults to “Allen”.

Returns:

Filtered DataFrame containing only the selected features

for the specified brain region.

Return type:

pd.DataFrame

Note

Either acronym or id should be provided, but not both. If neither is provided, the function will return None.

ephysatlas.plots.get_color_feat(x, cmap_name='viridis', min_val=None, max_val=None)[source]

Generate colors for feature values using colormaps.

This function normalizes feature values to the range [0, 1] and maps them to colors using a specified colormap. Useful for creating color-coded visualizations of feature values.

Parameters:
  • x (np.ndarray) – Array of feature values to colorize.

  • cmap_name (str, optional) – Name of the matplotlib colormap to use. Defaults to “viridis”.

  • min_val (float, optional) – Minimum value for normalization. If None, uses the minimum value in x. Defaults to None.

  • max_val (float, optional) – Maximum value for normalization. If None, uses the maximum value in x. Defaults to None.

Returns:

Array of RGBA colors with the same shape as x.

Return type:

np.ndarray

Note

The function performs min-max normalization and maps the normalized values to colors using the specified colormap. Values are clipped to the [0, 1] range during normalization.

ephysatlas.plots.get_color_br(pid_ch_df, br, mapping='Allen')[source]

Generate colors for brain regions.

This function extracts brain region IDs from a DataFrame and maps them to their corresponding RGB colors from the brain regions atlas.

Parameters:
  • pid_ch_df (pd.DataFrame) – DataFrame containing brain region mapping columns (e.g., “Allen_id”).

  • br (iblatlas.atlas.BrainRegions) – BrainRegions object containing region information and colors.

  • mapping (str, optional) – Brain region mapping system to use. Defaults to “Allen”.

Returns:

Array of RGB colors normalized to [0, 1] range.

Return type:

np.ndarray

Note

The function looks for a column named “{mapping}_id” in the DataFrame and uses the brain regions atlas to map these IDs to RGB colors.

ephysatlas.plots.plot_probe_rect(xy, color, ax, width=16, height=40)[source]

Plot probe channels as rectangles with specified colors.

This function uses matplotlib rectangles to visualize probe channels at their spatial coordinates with specified colors and dimensions.

Parameters:
  • xy (np.ndarray) – Array of shape (n_channels, 2) containing x,y coordinates for each channel in micrometers.

  • color (np.ndarray) – Array of shape (n_channels, 3) or (n_channels, 4) containing RGB or RGBA colors for each channel.

  • ax (matplotlib.axes.Axes) – Axes on which to plot the rectangles.

  • width (float, optional) – Width of each rectangle in micrometers. Defaults to 16.

  • height (float, optional) – Height of each rectangle in micrometers. Defaults to 40.

Returns:

The function modifies the provided axes.

Return type:

None

Note

The function automatically adjusts the plot limits to accommodate all rectangles. Each channel is represented by a filled rectangle centered at its spatial coordinates.

ephysatlas.plots.plot_probe_rect2(xy, color, ax, width=16, height=40, colorbar=False)[source]

Plot probe channels using imshow for better visualization.

This function uses matplotlib’s imshow to visualize probe channels as colored rectangles, providing better performance and visualization quality compared to individual rectangle patches.

Parameters:
  • xy (np.ndarray) – Array of shape (n_channels, 2) containing x,y coordinates for each channel in micrometers.

  • color (np.ndarray) – Array of shape (n_channels, 3) or (n_channels, 4) containing RGB or RGBA colors for each channel.

  • ax (matplotlib.axes.Axes) – Axes on which to plot the visualization.

  • width (float, optional) – Width of each channel representation in micrometers. Defaults to 16.

  • height (float, optional) – Height of each channel representation in micrometers. Defaults to 40.

  • colorbar (bool, optional) – Whether to add a colorbar to the plot. Defaults to False.

Returns:

The function modifies the provided axes.

Return type:

None

Note

The function stretches the probe in the X direction (factor of 3) to improve readability for very long thin probes. It creates a rasterized representation using numpy arrays and imshow for efficient rendering.

ephysatlas.plots.figure_features_channel_space(pid_df, features, xy, pid, fig=None, axs=None, br=None, mapping='Cosmos', plot_rect=<function plot_probe_rect2>, cmap='viridis', scaler=None, vmin=None, vmax=None)[source]

Create a figure displaying electrophysiological features and brain regions along a probe.

This function visualizes multiple features along a probe’s channels in physical space, as well as brain region information. It creates a multi-panel figure where each panel shows a different feature or brain region mapping.

Parameters:
  • pid_df (pd.DataFrame) – Dataframe containing channels and voltage information for a given probe ID (PID). Must contain columns for the specified features and brain region mapping.

  • features (list[str]) – List of feature names to display, e.g. [‘rms_lf’, ‘psd_delta’, ‘rms_ap’]. These must be column keys in pid_df.

  • xy (np.ndarray) – Matrix of spatial channel positions (in μm), with shape [N_channels x 2]. First column is lateral_um (x) and second column is axial_um (y).

  • pid (str) – Probe ID to be displayed in the figure title.

  • fig (matplotlib.figure.Figure, optional) – Existing figure to plot on. If None, a new figure is created.

  • axs (np.ndarray, optional) – Existing axes to plot on. If None, new axes are created.

  • br (iblatlas.atlas.BrainRegions, optional) – BrainRegions object for region color mapping. If None, a new one is created.

  • mapping (str, optional) – Brain region mapping to use. The function will look for columns named “{mapping}_id” in pid_df. Defaults to “Cosmos”.

  • plot_rect (callable, optional) – Function to use for plotting rectangles. Should accept xy, color, and ax parameters. Defaults to plot_probe_rect2.

  • cmap (str, optional) – Colormap name to use for feature visualization. Defaults to “viridis”.

  • scaler (object, optional) – Scaling to be applied to feature values before displaying. Should have a transform method (like sklearn.preprocessing.StandardScaler).

  • vmin (float, optional) – Minimum value for color normalization. If None, the minimum value in the data is used.

  • vmax (float, optional) – Maximum value for color normalization. If None, the maximum value in the data is used.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing the plots.

  • axs (np.ndarray): The axes objects for each subplot.

Return type:

tuple

Note

The function creates a multi-panel figure with brain region visualization, feature plots, and probe layout. It automatically handles figure sizing and subplot arrangement for optimal visualization.

Example

# Merge the voltage and channels dataframe df_voltage = pd.merge(df_voltage, df_channels, left_index=True, right_index=True).dropna() # Select a PID and create the single probe dataframe pid = ‘0228bcfd-632e-49bd-acd4-c334cf9213e9’ pid_df = df_voltage[df_voltage.index.get_level_values(0).isin([pid])].copy()

ephysatlas.plots.plot_features_distributions(df_features, x_list=None, title='')[source]

Create a grid of histograms displaying the distribution of electrophysiological features.

This function generates a multi-panel figure with histograms for each feature in x_list. Each histogram is color-coded according to feature values and accompanied by a colorbar. The function uses quantile-based limits to handle outliers in the data visualization.

Parameters:
  • df_features (pd.DataFrame) – DataFrame containing the feature values with feature names as columns.

  • x_list (list, optional) – List of feature names to plot. If None, uses all available voltage features. Defaults to None.

  • title (str, optional) – Title for the figure. Defaults to “”.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing all histograms.

  • axs (np.ndarray): Array of matplotlib.axes.Axes objects for each subplot.

Return type:

tuple

Note

The function creates a 4x12 grid layout with histograms and colorbars. Each histogram uses quantile-based limits (0.1-0.9 for color range, 0.005-0.995 for histogram range) to handle outliers gracefully. The PuOr colormap is used for feature value coloring.

Data Selection and Processing

Electrophysiological plotting and visualization module.

This module provides comprehensive plotting and visualization tools for electrophysiological data analysis, including feature distributions, probe visualizations, brain region mappings, and statistical plots.

The module includes: - Histogram plotting with quantile-based coloring - Cumulative probability plots for brain regions - Probe visualization in physical space - Feature distribution analysis - Brain region mapping and visualization - Statistical plotting utilities

Functions

plot_histogram

Create histograms with quantile-based color coding

plot_cumulative_probas

Plot cumulative probabilities of brain regions along probe depths

plot_results

Visualize model prediction results and feature distributions

select_series

Select data series based on features and brain region criteria

get_color_feat

Generate colors for feature values using colormaps

get_color_br

Generate colors for brain regions

plot_probe_rect

Plot probe channels as rectangles with specified colors

plot_probe_rect2

Plot probe channels using imshow for better visualization

figure_features_channel_space

Create comprehensive probe visualization with features and brain regions

plot_features_distributions

Create grid of histograms for feature distributions

Constants

QUANTILESlist

Default quantile values for histogram coloring

BINSint

Default number of bins for histograms

Examples

>>> from ephysatlas.plots import plot_histogram, plot_probe_rect2
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>>
>>> # Create sample data
>>> data = np.random.randn(1000)
>>>
>>> # Plot histogram
>>> plot_histogram(data, xlabel="Value", title="Sample Distribution")
>>>
>>> # Plot probe visualization
>>> xy = np.column_stack([np.arange(64), np.zeros(64)])
>>> colors = np.random.rand(64, 3)
>>> fig, ax = plt.subplots()
>>> plot_probe_rect2(xy, colors, ax)

Notes

This module integrates with the IBL (International Brain Laboratory) ecosystem and uses their styling conventions and brain region atlases. It provides both simple plotting functions and complex multi-panel visualizations for electrophysiological data analysis.

See Also

ephysatlas.features : Feature extraction and processing iblatlas.atlas : Brain region atlas functionality brainbox.ephys_plots : Additional electrophysiology plotting tools

ephysatlas.plots.plot_histogram(series, ax=None, quantiles=None, bins=None, xlabel=None, title=None, normalise=False)[source]

Create histograms with quantile-based color coding.

This function creates histograms with color coding based on quantile values, providing visual distinction between different ranges of the data distribution.

Parameters:
  • series (pd.Series or np.ndarray) – Data series to plot as histogram.

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

  • quantiles (list, optional) – Quantile values for color coding. Defaults to QUANTILES constant [0.01, 0.1, 0.9, 0.99].

  • bins (int, optional) – Number of histogram bins. Defaults to BINS constant (50).

  • xlabel (str, optional) – Label for the x-axis.

  • title (str, optional) – Title for the plot.

  • normalise (bool, optional) – Whether to normalize the histogram counts. Defaults to False.

Returns:

The function modifies the provided axes or creates a new plot.

Return type:

None

Note

The function uses the viridis colormap for quantile-based coloring. Sample count is displayed in the top-right corner of the plot.

ephysatlas.plots.plot_cumulative_probas(probas, depths, aids, regions=None, ax=None, legend=False)[source]

Plot cumulative probabilities of brain regions along probe depths.

Creates a stacked area plot showing the probability distribution of different brain regions at each depth along a probe trajectory. Each region is colored according to its standard atlas color.

Parameters:
  • probas (np.ndarray) – Array of shape (ndepths, nregions) containing probabilities for each region at each depth. Values should sum to 1 across regions for each depth.

  • depths (np.ndarray) – Vector of length ndepths containing the depth values along the probe trajectory.

  • aids (np.ndarray) – Vector of length nregions containing the atlas IDs for each region.

  • regions (iblatlas.BrainRegions, optional) – BrainRegions object containing region information. If None, a new instance is created.

  • ax (matplotlib.axes.Axes, optional) – Axes on which to plot. If None, the current axes will be used.

  • legend (bool, optional) – Whether to display a legend with region names. Defaults to False.

Returns:

The axes object containing the plot.

Return type:

matplotlib.axes.Axes

Note

The function creates a stacked area plot where each brain region is represented by a different color from the atlas. The y-axis represents depth along the probe.

ephysatlas.plots.plot_results(df, predicted_probas, dict_model, regions=None)[source]

Visualize model prediction results and feature distributions.

This function creates a comprehensive visualization of model prediction results, including feature heatmaps, cumulative probability plots for different folds, and entropy analysis across channels.

Parameters:
  • df (pd.DataFrame) – DataFrame containing channel data and features.

  • predicted_probas (np.ndarray) – Array of predicted probabilities with shape (n_folds, n_channels, n_classes) or (n_channels, n_classes).

  • dict_model (dict) – Model dictionary containing metadata including features and class information.

  • regions (iblatlas.BrainRegions, optional) – BrainRegions object for region visualization. If None, a new instance is created.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing all plots.

  • axs (np.ndarray): Array of matplotlib axes objects.

Return type:

tuple

Note

The function creates a multi-panel figure with feature heatmaps, probability plots for each fold, and entropy analysis. It automatically handles both single-fold and multi-fold prediction arrays.

ephysatlas.plots.select_series(df, features=None, acronym=None, id=None, mapping='Allen')[source]

Select data series based on features and brain region criteria.

This function filters a DataFrame to select specific features based on brain region criteria (acronym or ID) and returns the selected data series.

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

  • features (list, optional) – List of feature names to select. If None, uses all available voltage features. Defaults to None.

  • acronym (str, optional) – Brain region acronym to filter by. Mutually exclusive with id parameter.

  • id (int, optional) – Brain region ID to filter by. Mutually exclusive with acronym parameter.

  • mapping (str, optional) – Brain region mapping system to use. Defaults to “Allen”.

Returns:

Filtered DataFrame containing only the selected features

for the specified brain region.

Return type:

pd.DataFrame

Note

Either acronym or id should be provided, but not both. If neither is provided, the function will return None.

ephysatlas.plots.get_color_feat(x, cmap_name='viridis', min_val=None, max_val=None)[source]

Generate colors for feature values using colormaps.

This function normalizes feature values to the range [0, 1] and maps them to colors using a specified colormap. Useful for creating color-coded visualizations of feature values.

Parameters:
  • x (np.ndarray) – Array of feature values to colorize.

  • cmap_name (str, optional) – Name of the matplotlib colormap to use. Defaults to “viridis”.

  • min_val (float, optional) – Minimum value for normalization. If None, uses the minimum value in x. Defaults to None.

  • max_val (float, optional) – Maximum value for normalization. If None, uses the maximum value in x. Defaults to None.

Returns:

Array of RGBA colors with the same shape as x.

Return type:

np.ndarray

Note

The function performs min-max normalization and maps the normalized values to colors using the specified colormap. Values are clipped to the [0, 1] range during normalization.

ephysatlas.plots.get_color_br(pid_ch_df, br, mapping='Allen')[source]

Generate colors for brain regions.

This function extracts brain region IDs from a DataFrame and maps them to their corresponding RGB colors from the brain regions atlas.

Parameters:
  • pid_ch_df (pd.DataFrame) – DataFrame containing brain region mapping columns (e.g., “Allen_id”).

  • br (iblatlas.atlas.BrainRegions) – BrainRegions object containing region information and colors.

  • mapping (str, optional) – Brain region mapping system to use. Defaults to “Allen”.

Returns:

Array of RGB colors normalized to [0, 1] range.

Return type:

np.ndarray

Note

The function looks for a column named “{mapping}_id” in the DataFrame and uses the brain regions atlas to map these IDs to RGB colors.

ephysatlas.plots.plot_probe_rect(xy, color, ax, width=16, height=40)[source]

Plot probe channels as rectangles with specified colors.

This function uses matplotlib rectangles to visualize probe channels at their spatial coordinates with specified colors and dimensions.

Parameters:
  • xy (np.ndarray) – Array of shape (n_channels, 2) containing x,y coordinates for each channel in micrometers.

  • color (np.ndarray) – Array of shape (n_channels, 3) or (n_channels, 4) containing RGB or RGBA colors for each channel.

  • ax (matplotlib.axes.Axes) – Axes on which to plot the rectangles.

  • width (float, optional) – Width of each rectangle in micrometers. Defaults to 16.

  • height (float, optional) – Height of each rectangle in micrometers. Defaults to 40.

Returns:

The function modifies the provided axes.

Return type:

None

Note

The function automatically adjusts the plot limits to accommodate all rectangles. Each channel is represented by a filled rectangle centered at its spatial coordinates.

ephysatlas.plots.plot_probe_rect2(xy, color, ax, width=16, height=40, colorbar=False)[source]

Plot probe channels using imshow for better visualization.

This function uses matplotlib’s imshow to visualize probe channels as colored rectangles, providing better performance and visualization quality compared to individual rectangle patches.

Parameters:
  • xy (np.ndarray) – Array of shape (n_channels, 2) containing x,y coordinates for each channel in micrometers.

  • color (np.ndarray) – Array of shape (n_channels, 3) or (n_channels, 4) containing RGB or RGBA colors for each channel.

  • ax (matplotlib.axes.Axes) – Axes on which to plot the visualization.

  • width (float, optional) – Width of each channel representation in micrometers. Defaults to 16.

  • height (float, optional) – Height of each channel representation in micrometers. Defaults to 40.

  • colorbar (bool, optional) – Whether to add a colorbar to the plot. Defaults to False.

Returns:

The function modifies the provided axes.

Return type:

None

Note

The function stretches the probe in the X direction (factor of 3) to improve readability for very long thin probes. It creates a rasterized representation using numpy arrays and imshow for efficient rendering.

ephysatlas.plots.figure_features_channel_space(pid_df, features, xy, pid, fig=None, axs=None, br=None, mapping='Cosmos', plot_rect=<function plot_probe_rect2>, cmap='viridis', scaler=None, vmin=None, vmax=None)[source]

Create a figure displaying electrophysiological features and brain regions along a probe.

This function visualizes multiple features along a probe’s channels in physical space, as well as brain region information. It creates a multi-panel figure where each panel shows a different feature or brain region mapping.

Parameters:
  • pid_df (pd.DataFrame) – Dataframe containing channels and voltage information for a given probe ID (PID). Must contain columns for the specified features and brain region mapping.

  • features (list[str]) – List of feature names to display, e.g. [‘rms_lf’, ‘psd_delta’, ‘rms_ap’]. These must be column keys in pid_df.

  • xy (np.ndarray) – Matrix of spatial channel positions (in μm), with shape [N_channels x 2]. First column is lateral_um (x) and second column is axial_um (y).

  • pid (str) – Probe ID to be displayed in the figure title.

  • fig (matplotlib.figure.Figure, optional) – Existing figure to plot on. If None, a new figure is created.

  • axs (np.ndarray, optional) – Existing axes to plot on. If None, new axes are created.

  • br (iblatlas.atlas.BrainRegions, optional) – BrainRegions object for region color mapping. If None, a new one is created.

  • mapping (str, optional) – Brain region mapping to use. The function will look for columns named “{mapping}_id” in pid_df. Defaults to “Cosmos”.

  • plot_rect (callable, optional) – Function to use for plotting rectangles. Should accept xy, color, and ax parameters. Defaults to plot_probe_rect2.

  • cmap (str, optional) – Colormap name to use for feature visualization. Defaults to “viridis”.

  • scaler (object, optional) – Scaling to be applied to feature values before displaying. Should have a transform method (like sklearn.preprocessing.StandardScaler).

  • vmin (float, optional) – Minimum value for color normalization. If None, the minimum value in the data is used.

  • vmax (float, optional) – Maximum value for color normalization. If None, the maximum value in the data is used.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing the plots.

  • axs (np.ndarray): The axes objects for each subplot.

Return type:

tuple

Note

The function creates a multi-panel figure with brain region visualization, feature plots, and probe layout. It automatically handles figure sizing and subplot arrangement for optimal visualization.

Example

# Merge the voltage and channels dataframe df_voltage = pd.merge(df_voltage, df_channels, left_index=True, right_index=True).dropna() # Select a PID and create the single probe dataframe pid = ‘0228bcfd-632e-49bd-acd4-c334cf9213e9’ pid_df = df_voltage[df_voltage.index.get_level_values(0).isin([pid])].copy()

ephysatlas.plots.plot_features_distributions(df_features, x_list=None, title='')[source]

Create a grid of histograms displaying the distribution of electrophysiological features.

This function generates a multi-panel figure with histograms for each feature in x_list. Each histogram is color-coded according to feature values and accompanied by a colorbar. The function uses quantile-based limits to handle outliers in the data visualization.

Parameters:
  • df_features (pd.DataFrame) – DataFrame containing the feature values with feature names as columns.

  • x_list (list, optional) – List of feature names to plot. If None, uses all available voltage features. Defaults to None.

  • title (str, optional) – Title for the figure. Defaults to “”.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing all histograms.

  • axs (np.ndarray): Array of matplotlib.axes.Axes objects for each subplot.

Return type:

tuple

Note

The function creates a 4x12 grid layout with histograms and colorbars. Each histogram uses quantile-based limits (0.1-0.9 for color range, 0.005-0.995 for histogram range) to handle outliers gracefully. The PuOr colormap is used for feature value coloring.

Color Management

Electrophysiological plotting and visualization module.

This module provides comprehensive plotting and visualization tools for electrophysiological data analysis, including feature distributions, probe visualizations, brain region mappings, and statistical plots.

The module includes: - Histogram plotting with quantile-based coloring - Cumulative probability plots for brain regions - Probe visualization in physical space - Feature distribution analysis - Brain region mapping and visualization - Statistical plotting utilities

Functions

plot_histogram

Create histograms with quantile-based color coding

plot_cumulative_probas

Plot cumulative probabilities of brain regions along probe depths

plot_results

Visualize model prediction results and feature distributions

select_series

Select data series based on features and brain region criteria

get_color_feat

Generate colors for feature values using colormaps

get_color_br

Generate colors for brain regions

plot_probe_rect

Plot probe channels as rectangles with specified colors

plot_probe_rect2

Plot probe channels using imshow for better visualization

figure_features_channel_space

Create comprehensive probe visualization with features and brain regions

plot_features_distributions

Create grid of histograms for feature distributions

Constants

QUANTILESlist

Default quantile values for histogram coloring

BINSint

Default number of bins for histograms

Examples

>>> from ephysatlas.plots import plot_histogram, plot_probe_rect2
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>>
>>> # Create sample data
>>> data = np.random.randn(1000)
>>>
>>> # Plot histogram
>>> plot_histogram(data, xlabel="Value", title="Sample Distribution")
>>>
>>> # Plot probe visualization
>>> xy = np.column_stack([np.arange(64), np.zeros(64)])
>>> colors = np.random.rand(64, 3)
>>> fig, ax = plt.subplots()
>>> plot_probe_rect2(xy, colors, ax)

Notes

This module integrates with the IBL (International Brain Laboratory) ecosystem and uses their styling conventions and brain region atlases. It provides both simple plotting functions and complex multi-panel visualizations for electrophysiological data analysis.

See Also

ephysatlas.features : Feature extraction and processing iblatlas.atlas : Brain region atlas functionality brainbox.ephys_plots : Additional electrophysiology plotting tools

ephysatlas.plots.plot_histogram(series, ax=None, quantiles=None, bins=None, xlabel=None, title=None, normalise=False)[source]

Create histograms with quantile-based color coding.

This function creates histograms with color coding based on quantile values, providing visual distinction between different ranges of the data distribution.

Parameters:
  • series (pd.Series or np.ndarray) – Data series to plot as histogram.

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

  • quantiles (list, optional) – Quantile values for color coding. Defaults to QUANTILES constant [0.01, 0.1, 0.9, 0.99].

  • bins (int, optional) – Number of histogram bins. Defaults to BINS constant (50).

  • xlabel (str, optional) – Label for the x-axis.

  • title (str, optional) – Title for the plot.

  • normalise (bool, optional) – Whether to normalize the histogram counts. Defaults to False.

Returns:

The function modifies the provided axes or creates a new plot.

Return type:

None

Note

The function uses the viridis colormap for quantile-based coloring. Sample count is displayed in the top-right corner of the plot.

ephysatlas.plots.plot_cumulative_probas(probas, depths, aids, regions=None, ax=None, legend=False)[source]

Plot cumulative probabilities of brain regions along probe depths.

Creates a stacked area plot showing the probability distribution of different brain regions at each depth along a probe trajectory. Each region is colored according to its standard atlas color.

Parameters:
  • probas (np.ndarray) – Array of shape (ndepths, nregions) containing probabilities for each region at each depth. Values should sum to 1 across regions for each depth.

  • depths (np.ndarray) – Vector of length ndepths containing the depth values along the probe trajectory.

  • aids (np.ndarray) – Vector of length nregions containing the atlas IDs for each region.

  • regions (iblatlas.BrainRegions, optional) – BrainRegions object containing region information. If None, a new instance is created.

  • ax (matplotlib.axes.Axes, optional) – Axes on which to plot. If None, the current axes will be used.

  • legend (bool, optional) – Whether to display a legend with region names. Defaults to False.

Returns:

The axes object containing the plot.

Return type:

matplotlib.axes.Axes

Note

The function creates a stacked area plot where each brain region is represented by a different color from the atlas. The y-axis represents depth along the probe.

ephysatlas.plots.plot_results(df, predicted_probas, dict_model, regions=None)[source]

Visualize model prediction results and feature distributions.

This function creates a comprehensive visualization of model prediction results, including feature heatmaps, cumulative probability plots for different folds, and entropy analysis across channels.

Parameters:
  • df (pd.DataFrame) – DataFrame containing channel data and features.

  • predicted_probas (np.ndarray) – Array of predicted probabilities with shape (n_folds, n_channels, n_classes) or (n_channels, n_classes).

  • dict_model (dict) – Model dictionary containing metadata including features and class information.

  • regions (iblatlas.BrainRegions, optional) – BrainRegions object for region visualization. If None, a new instance is created.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing all plots.

  • axs (np.ndarray): Array of matplotlib axes objects.

Return type:

tuple

Note

The function creates a multi-panel figure with feature heatmaps, probability plots for each fold, and entropy analysis. It automatically handles both single-fold and multi-fold prediction arrays.

ephysatlas.plots.select_series(df, features=None, acronym=None, id=None, mapping='Allen')[source]

Select data series based on features and brain region criteria.

This function filters a DataFrame to select specific features based on brain region criteria (acronym or ID) and returns the selected data series.

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

  • features (list, optional) – List of feature names to select. If None, uses all available voltage features. Defaults to None.

  • acronym (str, optional) – Brain region acronym to filter by. Mutually exclusive with id parameter.

  • id (int, optional) – Brain region ID to filter by. Mutually exclusive with acronym parameter.

  • mapping (str, optional) – Brain region mapping system to use. Defaults to “Allen”.

Returns:

Filtered DataFrame containing only the selected features

for the specified brain region.

Return type:

pd.DataFrame

Note

Either acronym or id should be provided, but not both. If neither is provided, the function will return None.

ephysatlas.plots.get_color_feat(x, cmap_name='viridis', min_val=None, max_val=None)[source]

Generate colors for feature values using colormaps.

This function normalizes feature values to the range [0, 1] and maps them to colors using a specified colormap. Useful for creating color-coded visualizations of feature values.

Parameters:
  • x (np.ndarray) – Array of feature values to colorize.

  • cmap_name (str, optional) – Name of the matplotlib colormap to use. Defaults to “viridis”.

  • min_val (float, optional) – Minimum value for normalization. If None, uses the minimum value in x. Defaults to None.

  • max_val (float, optional) – Maximum value for normalization. If None, uses the maximum value in x. Defaults to None.

Returns:

Array of RGBA colors with the same shape as x.

Return type:

np.ndarray

Note

The function performs min-max normalization and maps the normalized values to colors using the specified colormap. Values are clipped to the [0, 1] range during normalization.

ephysatlas.plots.get_color_br(pid_ch_df, br, mapping='Allen')[source]

Generate colors for brain regions.

This function extracts brain region IDs from a DataFrame and maps them to their corresponding RGB colors from the brain regions atlas.

Parameters:
  • pid_ch_df (pd.DataFrame) – DataFrame containing brain region mapping columns (e.g., “Allen_id”).

  • br (iblatlas.atlas.BrainRegions) – BrainRegions object containing region information and colors.

  • mapping (str, optional) – Brain region mapping system to use. Defaults to “Allen”.

Returns:

Array of RGB colors normalized to [0, 1] range.

Return type:

np.ndarray

Note

The function looks for a column named “{mapping}_id” in the DataFrame and uses the brain regions atlas to map these IDs to RGB colors.

ephysatlas.plots.plot_probe_rect(xy, color, ax, width=16, height=40)[source]

Plot probe channels as rectangles with specified colors.

This function uses matplotlib rectangles to visualize probe channels at their spatial coordinates with specified colors and dimensions.

Parameters:
  • xy (np.ndarray) – Array of shape (n_channels, 2) containing x,y coordinates for each channel in micrometers.

  • color (np.ndarray) – Array of shape (n_channels, 3) or (n_channels, 4) containing RGB or RGBA colors for each channel.

  • ax (matplotlib.axes.Axes) – Axes on which to plot the rectangles.

  • width (float, optional) – Width of each rectangle in micrometers. Defaults to 16.

  • height (float, optional) – Height of each rectangle in micrometers. Defaults to 40.

Returns:

The function modifies the provided axes.

Return type:

None

Note

The function automatically adjusts the plot limits to accommodate all rectangles. Each channel is represented by a filled rectangle centered at its spatial coordinates.

ephysatlas.plots.plot_probe_rect2(xy, color, ax, width=16, height=40, colorbar=False)[source]

Plot probe channels using imshow for better visualization.

This function uses matplotlib’s imshow to visualize probe channels as colored rectangles, providing better performance and visualization quality compared to individual rectangle patches.

Parameters:
  • xy (np.ndarray) – Array of shape (n_channels, 2) containing x,y coordinates for each channel in micrometers.

  • color (np.ndarray) – Array of shape (n_channels, 3) or (n_channels, 4) containing RGB or RGBA colors for each channel.

  • ax (matplotlib.axes.Axes) – Axes on which to plot the visualization.

  • width (float, optional) – Width of each channel representation in micrometers. Defaults to 16.

  • height (float, optional) – Height of each channel representation in micrometers. Defaults to 40.

  • colorbar (bool, optional) – Whether to add a colorbar to the plot. Defaults to False.

Returns:

The function modifies the provided axes.

Return type:

None

Note

The function stretches the probe in the X direction (factor of 3) to improve readability for very long thin probes. It creates a rasterized representation using numpy arrays and imshow for efficient rendering.

ephysatlas.plots.figure_features_channel_space(pid_df, features, xy, pid, fig=None, axs=None, br=None, mapping='Cosmos', plot_rect=<function plot_probe_rect2>, cmap='viridis', scaler=None, vmin=None, vmax=None)[source]

Create a figure displaying electrophysiological features and brain regions along a probe.

This function visualizes multiple features along a probe’s channels in physical space, as well as brain region information. It creates a multi-panel figure where each panel shows a different feature or brain region mapping.

Parameters:
  • pid_df (pd.DataFrame) – Dataframe containing channels and voltage information for a given probe ID (PID). Must contain columns for the specified features and brain region mapping.

  • features (list[str]) – List of feature names to display, e.g. [‘rms_lf’, ‘psd_delta’, ‘rms_ap’]. These must be column keys in pid_df.

  • xy (np.ndarray) – Matrix of spatial channel positions (in μm), with shape [N_channels x 2]. First column is lateral_um (x) and second column is axial_um (y).

  • pid (str) – Probe ID to be displayed in the figure title.

  • fig (matplotlib.figure.Figure, optional) – Existing figure to plot on. If None, a new figure is created.

  • axs (np.ndarray, optional) – Existing axes to plot on. If None, new axes are created.

  • br (iblatlas.atlas.BrainRegions, optional) – BrainRegions object for region color mapping. If None, a new one is created.

  • mapping (str, optional) – Brain region mapping to use. The function will look for columns named “{mapping}_id” in pid_df. Defaults to “Cosmos”.

  • plot_rect (callable, optional) – Function to use for plotting rectangles. Should accept xy, color, and ax parameters. Defaults to plot_probe_rect2.

  • cmap (str, optional) – Colormap name to use for feature visualization. Defaults to “viridis”.

  • scaler (object, optional) – Scaling to be applied to feature values before displaying. Should have a transform method (like sklearn.preprocessing.StandardScaler).

  • vmin (float, optional) – Minimum value for color normalization. If None, the minimum value in the data is used.

  • vmax (float, optional) – Maximum value for color normalization. If None, the maximum value in the data is used.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing the plots.

  • axs (np.ndarray): The axes objects for each subplot.

Return type:

tuple

Note

The function creates a multi-panel figure with brain region visualization, feature plots, and probe layout. It automatically handles figure sizing and subplot arrangement for optimal visualization.

Example

# Merge the voltage and channels dataframe df_voltage = pd.merge(df_voltage, df_channels, left_index=True, right_index=True).dropna() # Select a PID and create the single probe dataframe pid = ‘0228bcfd-632e-49bd-acd4-c334cf9213e9’ pid_df = df_voltage[df_voltage.index.get_level_values(0).isin([pid])].copy()

ephysatlas.plots.plot_features_distributions(df_features, x_list=None, title='')[source]

Create a grid of histograms displaying the distribution of electrophysiological features.

This function generates a multi-panel figure with histograms for each feature in x_list. Each histogram is color-coded according to feature values and accompanied by a colorbar. The function uses quantile-based limits to handle outliers in the data visualization.

Parameters:
  • df_features (pd.DataFrame) – DataFrame containing the feature values with feature names as columns.

  • x_list (list, optional) – List of feature names to plot. If None, uses all available voltage features. Defaults to None.

  • title (str, optional) – Title for the figure. Defaults to “”.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing all histograms.

  • axs (np.ndarray): Array of matplotlib.axes.Axes objects for each subplot.

Return type:

tuple

Note

The function creates a 4x12 grid layout with histograms and colorbars. Each histogram uses quantile-based limits (0.1-0.9 for color range, 0.005-0.995 for histogram range) to handle outliers gracefully. The PuOr colormap is used for feature value coloring.

Model Results Visualization

Electrophysiological plotting and visualization module.

This module provides comprehensive plotting and visualization tools for electrophysiological data analysis, including feature distributions, probe visualizations, brain region mappings, and statistical plots.

The module includes: - Histogram plotting with quantile-based coloring - Cumulative probability plots for brain regions - Probe visualization in physical space - Feature distribution analysis - Brain region mapping and visualization - Statistical plotting utilities

Functions

plot_histogram

Create histograms with quantile-based color coding

plot_cumulative_probas

Plot cumulative probabilities of brain regions along probe depths

plot_results

Visualize model prediction results and feature distributions

select_series

Select data series based on features and brain region criteria

get_color_feat

Generate colors for feature values using colormaps

get_color_br

Generate colors for brain regions

plot_probe_rect

Plot probe channels as rectangles with specified colors

plot_probe_rect2

Plot probe channels using imshow for better visualization

figure_features_channel_space

Create comprehensive probe visualization with features and brain regions

plot_features_distributions

Create grid of histograms for feature distributions

Constants

QUANTILESlist

Default quantile values for histogram coloring

BINSint

Default number of bins for histograms

Examples

>>> from ephysatlas.plots import plot_histogram, plot_probe_rect2
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>>
>>> # Create sample data
>>> data = np.random.randn(1000)
>>>
>>> # Plot histogram
>>> plot_histogram(data, xlabel="Value", title="Sample Distribution")
>>>
>>> # Plot probe visualization
>>> xy = np.column_stack([np.arange(64), np.zeros(64)])
>>> colors = np.random.rand(64, 3)
>>> fig, ax = plt.subplots()
>>> plot_probe_rect2(xy, colors, ax)

Notes

This module integrates with the IBL (International Brain Laboratory) ecosystem and uses their styling conventions and brain region atlases. It provides both simple plotting functions and complex multi-panel visualizations for electrophysiological data analysis.

See Also

ephysatlas.features : Feature extraction and processing iblatlas.atlas : Brain region atlas functionality brainbox.ephys_plots : Additional electrophysiology plotting tools

ephysatlas.plots.plot_histogram(series, ax=None, quantiles=None, bins=None, xlabel=None, title=None, normalise=False)[source]

Create histograms with quantile-based color coding.

This function creates histograms with color coding based on quantile values, providing visual distinction between different ranges of the data distribution.

Parameters:
  • series (pd.Series or np.ndarray) – Data series to plot as histogram.

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

  • quantiles (list, optional) – Quantile values for color coding. Defaults to QUANTILES constant [0.01, 0.1, 0.9, 0.99].

  • bins (int, optional) – Number of histogram bins. Defaults to BINS constant (50).

  • xlabel (str, optional) – Label for the x-axis.

  • title (str, optional) – Title for the plot.

  • normalise (bool, optional) – Whether to normalize the histogram counts. Defaults to False.

Returns:

The function modifies the provided axes or creates a new plot.

Return type:

None

Note

The function uses the viridis colormap for quantile-based coloring. Sample count is displayed in the top-right corner of the plot.

ephysatlas.plots.plot_cumulative_probas(probas, depths, aids, regions=None, ax=None, legend=False)[source]

Plot cumulative probabilities of brain regions along probe depths.

Creates a stacked area plot showing the probability distribution of different brain regions at each depth along a probe trajectory. Each region is colored according to its standard atlas color.

Parameters:
  • probas (np.ndarray) – Array of shape (ndepths, nregions) containing probabilities for each region at each depth. Values should sum to 1 across regions for each depth.

  • depths (np.ndarray) – Vector of length ndepths containing the depth values along the probe trajectory.

  • aids (np.ndarray) – Vector of length nregions containing the atlas IDs for each region.

  • regions (iblatlas.BrainRegions, optional) – BrainRegions object containing region information. If None, a new instance is created.

  • ax (matplotlib.axes.Axes, optional) – Axes on which to plot. If None, the current axes will be used.

  • legend (bool, optional) – Whether to display a legend with region names. Defaults to False.

Returns:

The axes object containing the plot.

Return type:

matplotlib.axes.Axes

Note

The function creates a stacked area plot where each brain region is represented by a different color from the atlas. The y-axis represents depth along the probe.

ephysatlas.plots.plot_results(df, predicted_probas, dict_model, regions=None)[source]

Visualize model prediction results and feature distributions.

This function creates a comprehensive visualization of model prediction results, including feature heatmaps, cumulative probability plots for different folds, and entropy analysis across channels.

Parameters:
  • df (pd.DataFrame) – DataFrame containing channel data and features.

  • predicted_probas (np.ndarray) – Array of predicted probabilities with shape (n_folds, n_channels, n_classes) or (n_channels, n_classes).

  • dict_model (dict) – Model dictionary containing metadata including features and class information.

  • regions (iblatlas.BrainRegions, optional) – BrainRegions object for region visualization. If None, a new instance is created.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing all plots.

  • axs (np.ndarray): Array of matplotlib axes objects.

Return type:

tuple

Note

The function creates a multi-panel figure with feature heatmaps, probability plots for each fold, and entropy analysis. It automatically handles both single-fold and multi-fold prediction arrays.

ephysatlas.plots.select_series(df, features=None, acronym=None, id=None, mapping='Allen')[source]

Select data series based on features and brain region criteria.

This function filters a DataFrame to select specific features based on brain region criteria (acronym or ID) and returns the selected data series.

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

  • features (list, optional) – List of feature names to select. If None, uses all available voltage features. Defaults to None.

  • acronym (str, optional) – Brain region acronym to filter by. Mutually exclusive with id parameter.

  • id (int, optional) – Brain region ID to filter by. Mutually exclusive with acronym parameter.

  • mapping (str, optional) – Brain region mapping system to use. Defaults to “Allen”.

Returns:

Filtered DataFrame containing only the selected features

for the specified brain region.

Return type:

pd.DataFrame

Note

Either acronym or id should be provided, but not both. If neither is provided, the function will return None.

ephysatlas.plots.get_color_feat(x, cmap_name='viridis', min_val=None, max_val=None)[source]

Generate colors for feature values using colormaps.

This function normalizes feature values to the range [0, 1] and maps them to colors using a specified colormap. Useful for creating color-coded visualizations of feature values.

Parameters:
  • x (np.ndarray) – Array of feature values to colorize.

  • cmap_name (str, optional) – Name of the matplotlib colormap to use. Defaults to “viridis”.

  • min_val (float, optional) – Minimum value for normalization. If None, uses the minimum value in x. Defaults to None.

  • max_val (float, optional) – Maximum value for normalization. If None, uses the maximum value in x. Defaults to None.

Returns:

Array of RGBA colors with the same shape as x.

Return type:

np.ndarray

Note

The function performs min-max normalization and maps the normalized values to colors using the specified colormap. Values are clipped to the [0, 1] range during normalization.

ephysatlas.plots.get_color_br(pid_ch_df, br, mapping='Allen')[source]

Generate colors for brain regions.

This function extracts brain region IDs from a DataFrame and maps them to their corresponding RGB colors from the brain regions atlas.

Parameters:
  • pid_ch_df (pd.DataFrame) – DataFrame containing brain region mapping columns (e.g., “Allen_id”).

  • br (iblatlas.atlas.BrainRegions) – BrainRegions object containing region information and colors.

  • mapping (str, optional) – Brain region mapping system to use. Defaults to “Allen”.

Returns:

Array of RGB colors normalized to [0, 1] range.

Return type:

np.ndarray

Note

The function looks for a column named “{mapping}_id” in the DataFrame and uses the brain regions atlas to map these IDs to RGB colors.

ephysatlas.plots.plot_probe_rect(xy, color, ax, width=16, height=40)[source]

Plot probe channels as rectangles with specified colors.

This function uses matplotlib rectangles to visualize probe channels at their spatial coordinates with specified colors and dimensions.

Parameters:
  • xy (np.ndarray) – Array of shape (n_channels, 2) containing x,y coordinates for each channel in micrometers.

  • color (np.ndarray) – Array of shape (n_channels, 3) or (n_channels, 4) containing RGB or RGBA colors for each channel.

  • ax (matplotlib.axes.Axes) – Axes on which to plot the rectangles.

  • width (float, optional) – Width of each rectangle in micrometers. Defaults to 16.

  • height (float, optional) – Height of each rectangle in micrometers. Defaults to 40.

Returns:

The function modifies the provided axes.

Return type:

None

Note

The function automatically adjusts the plot limits to accommodate all rectangles. Each channel is represented by a filled rectangle centered at its spatial coordinates.

ephysatlas.plots.plot_probe_rect2(xy, color, ax, width=16, height=40, colorbar=False)[source]

Plot probe channels using imshow for better visualization.

This function uses matplotlib’s imshow to visualize probe channels as colored rectangles, providing better performance and visualization quality compared to individual rectangle patches.

Parameters:
  • xy (np.ndarray) – Array of shape (n_channels, 2) containing x,y coordinates for each channel in micrometers.

  • color (np.ndarray) – Array of shape (n_channels, 3) or (n_channels, 4) containing RGB or RGBA colors for each channel.

  • ax (matplotlib.axes.Axes) – Axes on which to plot the visualization.

  • width (float, optional) – Width of each channel representation in micrometers. Defaults to 16.

  • height (float, optional) – Height of each channel representation in micrometers. Defaults to 40.

  • colorbar (bool, optional) – Whether to add a colorbar to the plot. Defaults to False.

Returns:

The function modifies the provided axes.

Return type:

None

Note

The function stretches the probe in the X direction (factor of 3) to improve readability for very long thin probes. It creates a rasterized representation using numpy arrays and imshow for efficient rendering.

ephysatlas.plots.figure_features_channel_space(pid_df, features, xy, pid, fig=None, axs=None, br=None, mapping='Cosmos', plot_rect=<function plot_probe_rect2>, cmap='viridis', scaler=None, vmin=None, vmax=None)[source]

Create a figure displaying electrophysiological features and brain regions along a probe.

This function visualizes multiple features along a probe’s channels in physical space, as well as brain region information. It creates a multi-panel figure where each panel shows a different feature or brain region mapping.

Parameters:
  • pid_df (pd.DataFrame) – Dataframe containing channels and voltage information for a given probe ID (PID). Must contain columns for the specified features and brain region mapping.

  • features (list[str]) – List of feature names to display, e.g. [‘rms_lf’, ‘psd_delta’, ‘rms_ap’]. These must be column keys in pid_df.

  • xy (np.ndarray) – Matrix of spatial channel positions (in μm), with shape [N_channels x 2]. First column is lateral_um (x) and second column is axial_um (y).

  • pid (str) – Probe ID to be displayed in the figure title.

  • fig (matplotlib.figure.Figure, optional) – Existing figure to plot on. If None, a new figure is created.

  • axs (np.ndarray, optional) – Existing axes to plot on. If None, new axes are created.

  • br (iblatlas.atlas.BrainRegions, optional) – BrainRegions object for region color mapping. If None, a new one is created.

  • mapping (str, optional) – Brain region mapping to use. The function will look for columns named “{mapping}_id” in pid_df. Defaults to “Cosmos”.

  • plot_rect (callable, optional) – Function to use for plotting rectangles. Should accept xy, color, and ax parameters. Defaults to plot_probe_rect2.

  • cmap (str, optional) – Colormap name to use for feature visualization. Defaults to “viridis”.

  • scaler (object, optional) – Scaling to be applied to feature values before displaying. Should have a transform method (like sklearn.preprocessing.StandardScaler).

  • vmin (float, optional) – Minimum value for color normalization. If None, the minimum value in the data is used.

  • vmax (float, optional) – Maximum value for color normalization. If None, the maximum value in the data is used.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing the plots.

  • axs (np.ndarray): The axes objects for each subplot.

Return type:

tuple

Note

The function creates a multi-panel figure with brain region visualization, feature plots, and probe layout. It automatically handles figure sizing and subplot arrangement for optimal visualization.

Example

# Merge the voltage and channels dataframe df_voltage = pd.merge(df_voltage, df_channels, left_index=True, right_index=True).dropna() # Select a PID and create the single probe dataframe pid = ‘0228bcfd-632e-49bd-acd4-c334cf9213e9’ pid_df = df_voltage[df_voltage.index.get_level_values(0).isin([pid])].copy()

ephysatlas.plots.plot_features_distributions(df_features, x_list=None, title='')[source]

Create a grid of histograms displaying the distribution of electrophysiological features.

This function generates a multi-panel figure with histograms for each feature in x_list. Each histogram is color-coded according to feature values and accompanied by a colorbar. The function uses quantile-based limits to handle outliers in the data visualization.

Parameters:
  • df_features (pd.DataFrame) – DataFrame containing the feature values with feature names as columns.

  • x_list (list, optional) – List of feature names to plot. If None, uses all available voltage features. Defaults to None.

  • title (str, optional) – Title for the figure. Defaults to “”.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing all histograms.

  • axs (np.ndarray): Array of matplotlib.axes.Axes objects for each subplot.

Return type:

tuple

Note

The function creates a 4x12 grid layout with histograms and colorbars. Each histogram uses quantile-based limits (0.1-0.9 for color range, 0.005-0.995 for histogram range) to handle outliers gracefully. The PuOr colormap is used for feature value coloring.

Probe Visualization

Electrophysiological plotting and visualization module.

This module provides comprehensive plotting and visualization tools for electrophysiological data analysis, including feature distributions, probe visualizations, brain region mappings, and statistical plots.

The module includes: - Histogram plotting with quantile-based coloring - Cumulative probability plots for brain regions - Probe visualization in physical space - Feature distribution analysis - Brain region mapping and visualization - Statistical plotting utilities

Functions

plot_histogram

Create histograms with quantile-based color coding

plot_cumulative_probas

Plot cumulative probabilities of brain regions along probe depths

plot_results

Visualize model prediction results and feature distributions

select_series

Select data series based on features and brain region criteria

get_color_feat

Generate colors for feature values using colormaps

get_color_br

Generate colors for brain regions

plot_probe_rect

Plot probe channels as rectangles with specified colors

plot_probe_rect2

Plot probe channels using imshow for better visualization

figure_features_channel_space

Create comprehensive probe visualization with features and brain regions

plot_features_distributions

Create grid of histograms for feature distributions

Constants

QUANTILESlist

Default quantile values for histogram coloring

BINSint

Default number of bins for histograms

Examples

>>> from ephysatlas.plots import plot_histogram, plot_probe_rect2
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>>
>>> # Create sample data
>>> data = np.random.randn(1000)
>>>
>>> # Plot histogram
>>> plot_histogram(data, xlabel="Value", title="Sample Distribution")
>>>
>>> # Plot probe visualization
>>> xy = np.column_stack([np.arange(64), np.zeros(64)])
>>> colors = np.random.rand(64, 3)
>>> fig, ax = plt.subplots()
>>> plot_probe_rect2(xy, colors, ax)

Notes

This module integrates with the IBL (International Brain Laboratory) ecosystem and uses their styling conventions and brain region atlases. It provides both simple plotting functions and complex multi-panel visualizations for electrophysiological data analysis.

See Also

ephysatlas.features : Feature extraction and processing iblatlas.atlas : Brain region atlas functionality brainbox.ephys_plots : Additional electrophysiology plotting tools

ephysatlas.plots.plot_histogram(series, ax=None, quantiles=None, bins=None, xlabel=None, title=None, normalise=False)[source]

Create histograms with quantile-based color coding.

This function creates histograms with color coding based on quantile values, providing visual distinction between different ranges of the data distribution.

Parameters:
  • series (pd.Series or np.ndarray) – Data series to plot as histogram.

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

  • quantiles (list, optional) – Quantile values for color coding. Defaults to QUANTILES constant [0.01, 0.1, 0.9, 0.99].

  • bins (int, optional) – Number of histogram bins. Defaults to BINS constant (50).

  • xlabel (str, optional) – Label for the x-axis.

  • title (str, optional) – Title for the plot.

  • normalise (bool, optional) – Whether to normalize the histogram counts. Defaults to False.

Returns:

The function modifies the provided axes or creates a new plot.

Return type:

None

Note

The function uses the viridis colormap for quantile-based coloring. Sample count is displayed in the top-right corner of the plot.

ephysatlas.plots.plot_cumulative_probas(probas, depths, aids, regions=None, ax=None, legend=False)[source]

Plot cumulative probabilities of brain regions along probe depths.

Creates a stacked area plot showing the probability distribution of different brain regions at each depth along a probe trajectory. Each region is colored according to its standard atlas color.

Parameters:
  • probas (np.ndarray) – Array of shape (ndepths, nregions) containing probabilities for each region at each depth. Values should sum to 1 across regions for each depth.

  • depths (np.ndarray) – Vector of length ndepths containing the depth values along the probe trajectory.

  • aids (np.ndarray) – Vector of length nregions containing the atlas IDs for each region.

  • regions (iblatlas.BrainRegions, optional) – BrainRegions object containing region information. If None, a new instance is created.

  • ax (matplotlib.axes.Axes, optional) – Axes on which to plot. If None, the current axes will be used.

  • legend (bool, optional) – Whether to display a legend with region names. Defaults to False.

Returns:

The axes object containing the plot.

Return type:

matplotlib.axes.Axes

Note

The function creates a stacked area plot where each brain region is represented by a different color from the atlas. The y-axis represents depth along the probe.

ephysatlas.plots.plot_results(df, predicted_probas, dict_model, regions=None)[source]

Visualize model prediction results and feature distributions.

This function creates a comprehensive visualization of model prediction results, including feature heatmaps, cumulative probability plots for different folds, and entropy analysis across channels.

Parameters:
  • df (pd.DataFrame) – DataFrame containing channel data and features.

  • predicted_probas (np.ndarray) – Array of predicted probabilities with shape (n_folds, n_channels, n_classes) or (n_channels, n_classes).

  • dict_model (dict) – Model dictionary containing metadata including features and class information.

  • regions (iblatlas.BrainRegions, optional) – BrainRegions object for region visualization. If None, a new instance is created.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing all plots.

  • axs (np.ndarray): Array of matplotlib axes objects.

Return type:

tuple

Note

The function creates a multi-panel figure with feature heatmaps, probability plots for each fold, and entropy analysis. It automatically handles both single-fold and multi-fold prediction arrays.

ephysatlas.plots.select_series(df, features=None, acronym=None, id=None, mapping='Allen')[source]

Select data series based on features and brain region criteria.

This function filters a DataFrame to select specific features based on brain region criteria (acronym or ID) and returns the selected data series.

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

  • features (list, optional) – List of feature names to select. If None, uses all available voltage features. Defaults to None.

  • acronym (str, optional) – Brain region acronym to filter by. Mutually exclusive with id parameter.

  • id (int, optional) – Brain region ID to filter by. Mutually exclusive with acronym parameter.

  • mapping (str, optional) – Brain region mapping system to use. Defaults to “Allen”.

Returns:

Filtered DataFrame containing only the selected features

for the specified brain region.

Return type:

pd.DataFrame

Note

Either acronym or id should be provided, but not both. If neither is provided, the function will return None.

ephysatlas.plots.get_color_feat(x, cmap_name='viridis', min_val=None, max_val=None)[source]

Generate colors for feature values using colormaps.

This function normalizes feature values to the range [0, 1] and maps them to colors using a specified colormap. Useful for creating color-coded visualizations of feature values.

Parameters:
  • x (np.ndarray) – Array of feature values to colorize.

  • cmap_name (str, optional) – Name of the matplotlib colormap to use. Defaults to “viridis”.

  • min_val (float, optional) – Minimum value for normalization. If None, uses the minimum value in x. Defaults to None.

  • max_val (float, optional) – Maximum value for normalization. If None, uses the maximum value in x. Defaults to None.

Returns:

Array of RGBA colors with the same shape as x.

Return type:

np.ndarray

Note

The function performs min-max normalization and maps the normalized values to colors using the specified colormap. Values are clipped to the [0, 1] range during normalization.

ephysatlas.plots.get_color_br(pid_ch_df, br, mapping='Allen')[source]

Generate colors for brain regions.

This function extracts brain region IDs from a DataFrame and maps them to their corresponding RGB colors from the brain regions atlas.

Parameters:
  • pid_ch_df (pd.DataFrame) – DataFrame containing brain region mapping columns (e.g., “Allen_id”).

  • br (iblatlas.atlas.BrainRegions) – BrainRegions object containing region information and colors.

  • mapping (str, optional) – Brain region mapping system to use. Defaults to “Allen”.

Returns:

Array of RGB colors normalized to [0, 1] range.

Return type:

np.ndarray

Note

The function looks for a column named “{mapping}_id” in the DataFrame and uses the brain regions atlas to map these IDs to RGB colors.

ephysatlas.plots.plot_probe_rect(xy, color, ax, width=16, height=40)[source]

Plot probe channels as rectangles with specified colors.

This function uses matplotlib rectangles to visualize probe channels at their spatial coordinates with specified colors and dimensions.

Parameters:
  • xy (np.ndarray) – Array of shape (n_channels, 2) containing x,y coordinates for each channel in micrometers.

  • color (np.ndarray) – Array of shape (n_channels, 3) or (n_channels, 4) containing RGB or RGBA colors for each channel.

  • ax (matplotlib.axes.Axes) – Axes on which to plot the rectangles.

  • width (float, optional) – Width of each rectangle in micrometers. Defaults to 16.

  • height (float, optional) – Height of each rectangle in micrometers. Defaults to 40.

Returns:

The function modifies the provided axes.

Return type:

None

Note

The function automatically adjusts the plot limits to accommodate all rectangles. Each channel is represented by a filled rectangle centered at its spatial coordinates.

ephysatlas.plots.plot_probe_rect2(xy, color, ax, width=16, height=40, colorbar=False)[source]

Plot probe channels using imshow for better visualization.

This function uses matplotlib’s imshow to visualize probe channels as colored rectangles, providing better performance and visualization quality compared to individual rectangle patches.

Parameters:
  • xy (np.ndarray) – Array of shape (n_channels, 2) containing x,y coordinates for each channel in micrometers.

  • color (np.ndarray) – Array of shape (n_channels, 3) or (n_channels, 4) containing RGB or RGBA colors for each channel.

  • ax (matplotlib.axes.Axes) – Axes on which to plot the visualization.

  • width (float, optional) – Width of each channel representation in micrometers. Defaults to 16.

  • height (float, optional) – Height of each channel representation in micrometers. Defaults to 40.

  • colorbar (bool, optional) – Whether to add a colorbar to the plot. Defaults to False.

Returns:

The function modifies the provided axes.

Return type:

None

Note

The function stretches the probe in the X direction (factor of 3) to improve readability for very long thin probes. It creates a rasterized representation using numpy arrays and imshow for efficient rendering.

ephysatlas.plots.figure_features_channel_space(pid_df, features, xy, pid, fig=None, axs=None, br=None, mapping='Cosmos', plot_rect=<function plot_probe_rect2>, cmap='viridis', scaler=None, vmin=None, vmax=None)[source]

Create a figure displaying electrophysiological features and brain regions along a probe.

This function visualizes multiple features along a probe’s channels in physical space, as well as brain region information. It creates a multi-panel figure where each panel shows a different feature or brain region mapping.

Parameters:
  • pid_df (pd.DataFrame) – Dataframe containing channels and voltage information for a given probe ID (PID). Must contain columns for the specified features and brain region mapping.

  • features (list[str]) – List of feature names to display, e.g. [‘rms_lf’, ‘psd_delta’, ‘rms_ap’]. These must be column keys in pid_df.

  • xy (np.ndarray) – Matrix of spatial channel positions (in μm), with shape [N_channels x 2]. First column is lateral_um (x) and second column is axial_um (y).

  • pid (str) – Probe ID to be displayed in the figure title.

  • fig (matplotlib.figure.Figure, optional) – Existing figure to plot on. If None, a new figure is created.

  • axs (np.ndarray, optional) – Existing axes to plot on. If None, new axes are created.

  • br (iblatlas.atlas.BrainRegions, optional) – BrainRegions object for region color mapping. If None, a new one is created.

  • mapping (str, optional) – Brain region mapping to use. The function will look for columns named “{mapping}_id” in pid_df. Defaults to “Cosmos”.

  • plot_rect (callable, optional) – Function to use for plotting rectangles. Should accept xy, color, and ax parameters. Defaults to plot_probe_rect2.

  • cmap (str, optional) – Colormap name to use for feature visualization. Defaults to “viridis”.

  • scaler (object, optional) – Scaling to be applied to feature values before displaying. Should have a transform method (like sklearn.preprocessing.StandardScaler).

  • vmin (float, optional) – Minimum value for color normalization. If None, the minimum value in the data is used.

  • vmax (float, optional) – Maximum value for color normalization. If None, the maximum value in the data is used.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing the plots.

  • axs (np.ndarray): The axes objects for each subplot.

Return type:

tuple

Note

The function creates a multi-panel figure with brain region visualization, feature plots, and probe layout. It automatically handles figure sizing and subplot arrangement for optimal visualization.

Example

# Merge the voltage and channels dataframe df_voltage = pd.merge(df_voltage, df_channels, left_index=True, right_index=True).dropna() # Select a PID and create the single probe dataframe pid = ‘0228bcfd-632e-49bd-acd4-c334cf9213e9’ pid_df = df_voltage[df_voltage.index.get_level_values(0).isin([pid])].copy()

ephysatlas.plots.plot_features_distributions(df_features, x_list=None, title='')[source]

Create a grid of histograms displaying the distribution of electrophysiological features.

This function generates a multi-panel figure with histograms for each feature in x_list. Each histogram is color-coded according to feature values and accompanied by a colorbar. The function uses quantile-based limits to handle outliers in the data visualization.

Parameters:
  • df_features (pd.DataFrame) – DataFrame containing the feature values with feature names as columns.

  • x_list (list, optional) – List of feature names to plot. If None, uses all available voltage features. Defaults to None.

  • title (str, optional) – Title for the figure. Defaults to “”.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing all histograms.

  • axs (np.ndarray): Array of matplotlib.axes.Axes objects for each subplot.

Return type:

tuple

Note

The function creates a 4x12 grid layout with histograms and colorbars. Each histogram uses quantile-based limits (0.1-0.9 for color range, 0.005-0.995 for histogram range) to handle outliers gracefully. The PuOr colormap is used for feature value coloring.

Feature Visualization

Electrophysiological plotting and visualization module.

This module provides comprehensive plotting and visualization tools for electrophysiological data analysis, including feature distributions, probe visualizations, brain region mappings, and statistical plots.

The module includes: - Histogram plotting with quantile-based coloring - Cumulative probability plots for brain regions - Probe visualization in physical space - Feature distribution analysis - Brain region mapping and visualization - Statistical plotting utilities

Functions

plot_histogram

Create histograms with quantile-based color coding

plot_cumulative_probas

Plot cumulative probabilities of brain regions along probe depths

plot_results

Visualize model prediction results and feature distributions

select_series

Select data series based on features and brain region criteria

get_color_feat

Generate colors for feature values using colormaps

get_color_br

Generate colors for brain regions

plot_probe_rect

Plot probe channels as rectangles with specified colors

plot_probe_rect2

Plot probe channels using imshow for better visualization

figure_features_channel_space

Create comprehensive probe visualization with features and brain regions

plot_features_distributions

Create grid of histograms for feature distributions

Constants

QUANTILESlist

Default quantile values for histogram coloring

BINSint

Default number of bins for histograms

Examples

>>> from ephysatlas.plots import plot_histogram, plot_probe_rect2
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>>
>>> # Create sample data
>>> data = np.random.randn(1000)
>>>
>>> # Plot histogram
>>> plot_histogram(data, xlabel="Value", title="Sample Distribution")
>>>
>>> # Plot probe visualization
>>> xy = np.column_stack([np.arange(64), np.zeros(64)])
>>> colors = np.random.rand(64, 3)
>>> fig, ax = plt.subplots()
>>> plot_probe_rect2(xy, colors, ax)

Notes

This module integrates with the IBL (International Brain Laboratory) ecosystem and uses their styling conventions and brain region atlases. It provides both simple plotting functions and complex multi-panel visualizations for electrophysiological data analysis.

See Also

ephysatlas.features : Feature extraction and processing iblatlas.atlas : Brain region atlas functionality brainbox.ephys_plots : Additional electrophysiology plotting tools

ephysatlas.plots.plot_histogram(series, ax=None, quantiles=None, bins=None, xlabel=None, title=None, normalise=False)[source]

Create histograms with quantile-based color coding.

This function creates histograms with color coding based on quantile values, providing visual distinction between different ranges of the data distribution.

Parameters:
  • series (pd.Series or np.ndarray) – Data series to plot as histogram.

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

  • quantiles (list, optional) – Quantile values for color coding. Defaults to QUANTILES constant [0.01, 0.1, 0.9, 0.99].

  • bins (int, optional) – Number of histogram bins. Defaults to BINS constant (50).

  • xlabel (str, optional) – Label for the x-axis.

  • title (str, optional) – Title for the plot.

  • normalise (bool, optional) – Whether to normalize the histogram counts. Defaults to False.

Returns:

The function modifies the provided axes or creates a new plot.

Return type:

None

Note

The function uses the viridis colormap for quantile-based coloring. Sample count is displayed in the top-right corner of the plot.

ephysatlas.plots.plot_cumulative_probas(probas, depths, aids, regions=None, ax=None, legend=False)[source]

Plot cumulative probabilities of brain regions along probe depths.

Creates a stacked area plot showing the probability distribution of different brain regions at each depth along a probe trajectory. Each region is colored according to its standard atlas color.

Parameters:
  • probas (np.ndarray) – Array of shape (ndepths, nregions) containing probabilities for each region at each depth. Values should sum to 1 across regions for each depth.

  • depths (np.ndarray) – Vector of length ndepths containing the depth values along the probe trajectory.

  • aids (np.ndarray) – Vector of length nregions containing the atlas IDs for each region.

  • regions (iblatlas.BrainRegions, optional) – BrainRegions object containing region information. If None, a new instance is created.

  • ax (matplotlib.axes.Axes, optional) – Axes on which to plot. If None, the current axes will be used.

  • legend (bool, optional) – Whether to display a legend with region names. Defaults to False.

Returns:

The axes object containing the plot.

Return type:

matplotlib.axes.Axes

Note

The function creates a stacked area plot where each brain region is represented by a different color from the atlas. The y-axis represents depth along the probe.

ephysatlas.plots.plot_results(df, predicted_probas, dict_model, regions=None)[source]

Visualize model prediction results and feature distributions.

This function creates a comprehensive visualization of model prediction results, including feature heatmaps, cumulative probability plots for different folds, and entropy analysis across channels.

Parameters:
  • df (pd.DataFrame) – DataFrame containing channel data and features.

  • predicted_probas (np.ndarray) – Array of predicted probabilities with shape (n_folds, n_channels, n_classes) or (n_channels, n_classes).

  • dict_model (dict) – Model dictionary containing metadata including features and class information.

  • regions (iblatlas.BrainRegions, optional) – BrainRegions object for region visualization. If None, a new instance is created.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing all plots.

  • axs (np.ndarray): Array of matplotlib axes objects.

Return type:

tuple

Note

The function creates a multi-panel figure with feature heatmaps, probability plots for each fold, and entropy analysis. It automatically handles both single-fold and multi-fold prediction arrays.

ephysatlas.plots.select_series(df, features=None, acronym=None, id=None, mapping='Allen')[source]

Select data series based on features and brain region criteria.

This function filters a DataFrame to select specific features based on brain region criteria (acronym or ID) and returns the selected data series.

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

  • features (list, optional) – List of feature names to select. If None, uses all available voltage features. Defaults to None.

  • acronym (str, optional) – Brain region acronym to filter by. Mutually exclusive with id parameter.

  • id (int, optional) – Brain region ID to filter by. Mutually exclusive with acronym parameter.

  • mapping (str, optional) – Brain region mapping system to use. Defaults to “Allen”.

Returns:

Filtered DataFrame containing only the selected features

for the specified brain region.

Return type:

pd.DataFrame

Note

Either acronym or id should be provided, but not both. If neither is provided, the function will return None.

ephysatlas.plots.get_color_feat(x, cmap_name='viridis', min_val=None, max_val=None)[source]

Generate colors for feature values using colormaps.

This function normalizes feature values to the range [0, 1] and maps them to colors using a specified colormap. Useful for creating color-coded visualizations of feature values.

Parameters:
  • x (np.ndarray) – Array of feature values to colorize.

  • cmap_name (str, optional) – Name of the matplotlib colormap to use. Defaults to “viridis”.

  • min_val (float, optional) – Minimum value for normalization. If None, uses the minimum value in x. Defaults to None.

  • max_val (float, optional) – Maximum value for normalization. If None, uses the maximum value in x. Defaults to None.

Returns:

Array of RGBA colors with the same shape as x.

Return type:

np.ndarray

Note

The function performs min-max normalization and maps the normalized values to colors using the specified colormap. Values are clipped to the [0, 1] range during normalization.

ephysatlas.plots.get_color_br(pid_ch_df, br, mapping='Allen')[source]

Generate colors for brain regions.

This function extracts brain region IDs from a DataFrame and maps them to their corresponding RGB colors from the brain regions atlas.

Parameters:
  • pid_ch_df (pd.DataFrame) – DataFrame containing brain region mapping columns (e.g., “Allen_id”).

  • br (iblatlas.atlas.BrainRegions) – BrainRegions object containing region information and colors.

  • mapping (str, optional) – Brain region mapping system to use. Defaults to “Allen”.

Returns:

Array of RGB colors normalized to [0, 1] range.

Return type:

np.ndarray

Note

The function looks for a column named “{mapping}_id” in the DataFrame and uses the brain regions atlas to map these IDs to RGB colors.

ephysatlas.plots.plot_probe_rect(xy, color, ax, width=16, height=40)[source]

Plot probe channels as rectangles with specified colors.

This function uses matplotlib rectangles to visualize probe channels at their spatial coordinates with specified colors and dimensions.

Parameters:
  • xy (np.ndarray) – Array of shape (n_channels, 2) containing x,y coordinates for each channel in micrometers.

  • color (np.ndarray) – Array of shape (n_channels, 3) or (n_channels, 4) containing RGB or RGBA colors for each channel.

  • ax (matplotlib.axes.Axes) – Axes on which to plot the rectangles.

  • width (float, optional) – Width of each rectangle in micrometers. Defaults to 16.

  • height (float, optional) – Height of each rectangle in micrometers. Defaults to 40.

Returns:

The function modifies the provided axes.

Return type:

None

Note

The function automatically adjusts the plot limits to accommodate all rectangles. Each channel is represented by a filled rectangle centered at its spatial coordinates.

ephysatlas.plots.plot_probe_rect2(xy, color, ax, width=16, height=40, colorbar=False)[source]

Plot probe channels using imshow for better visualization.

This function uses matplotlib’s imshow to visualize probe channels as colored rectangles, providing better performance and visualization quality compared to individual rectangle patches.

Parameters:
  • xy (np.ndarray) – Array of shape (n_channels, 2) containing x,y coordinates for each channel in micrometers.

  • color (np.ndarray) – Array of shape (n_channels, 3) or (n_channels, 4) containing RGB or RGBA colors for each channel.

  • ax (matplotlib.axes.Axes) – Axes on which to plot the visualization.

  • width (float, optional) – Width of each channel representation in micrometers. Defaults to 16.

  • height (float, optional) – Height of each channel representation in micrometers. Defaults to 40.

  • colorbar (bool, optional) – Whether to add a colorbar to the plot. Defaults to False.

Returns:

The function modifies the provided axes.

Return type:

None

Note

The function stretches the probe in the X direction (factor of 3) to improve readability for very long thin probes. It creates a rasterized representation using numpy arrays and imshow for efficient rendering.

ephysatlas.plots.figure_features_channel_space(pid_df, features, xy, pid, fig=None, axs=None, br=None, mapping='Cosmos', plot_rect=<function plot_probe_rect2>, cmap='viridis', scaler=None, vmin=None, vmax=None)[source]

Create a figure displaying electrophysiological features and brain regions along a probe.

This function visualizes multiple features along a probe’s channels in physical space, as well as brain region information. It creates a multi-panel figure where each panel shows a different feature or brain region mapping.

Parameters:
  • pid_df (pd.DataFrame) – Dataframe containing channels and voltage information for a given probe ID (PID). Must contain columns for the specified features and brain region mapping.

  • features (list[str]) – List of feature names to display, e.g. [‘rms_lf’, ‘psd_delta’, ‘rms_ap’]. These must be column keys in pid_df.

  • xy (np.ndarray) – Matrix of spatial channel positions (in μm), with shape [N_channels x 2]. First column is lateral_um (x) and second column is axial_um (y).

  • pid (str) – Probe ID to be displayed in the figure title.

  • fig (matplotlib.figure.Figure, optional) – Existing figure to plot on. If None, a new figure is created.

  • axs (np.ndarray, optional) – Existing axes to plot on. If None, new axes are created.

  • br (iblatlas.atlas.BrainRegions, optional) – BrainRegions object for region color mapping. If None, a new one is created.

  • mapping (str, optional) – Brain region mapping to use. The function will look for columns named “{mapping}_id” in pid_df. Defaults to “Cosmos”.

  • plot_rect (callable, optional) – Function to use for plotting rectangles. Should accept xy, color, and ax parameters. Defaults to plot_probe_rect2.

  • cmap (str, optional) – Colormap name to use for feature visualization. Defaults to “viridis”.

  • scaler (object, optional) – Scaling to be applied to feature values before displaying. Should have a transform method (like sklearn.preprocessing.StandardScaler).

  • vmin (float, optional) – Minimum value for color normalization. If None, the minimum value in the data is used.

  • vmax (float, optional) – Maximum value for color normalization. If None, the maximum value in the data is used.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing the plots.

  • axs (np.ndarray): The axes objects for each subplot.

Return type:

tuple

Note

The function creates a multi-panel figure with brain region visualization, feature plots, and probe layout. It automatically handles figure sizing and subplot arrangement for optimal visualization.

Example

# Merge the voltage and channels dataframe df_voltage = pd.merge(df_voltage, df_channels, left_index=True, right_index=True).dropna() # Select a PID and create the single probe dataframe pid = ‘0228bcfd-632e-49bd-acd4-c334cf9213e9’ pid_df = df_voltage[df_voltage.index.get_level_values(0).isin([pid])].copy()

ephysatlas.plots.plot_features_distributions(df_features, x_list=None, title='')[source]

Create a grid of histograms displaying the distribution of electrophysiological features.

This function generates a multi-panel figure with histograms for each feature in x_list. Each histogram is color-coded according to feature values and accompanied by a colorbar. The function uses quantile-based limits to handle outliers in the data visualization.

Parameters:
  • df_features (pd.DataFrame) – DataFrame containing the feature values with feature names as columns.

  • x_list (list, optional) – List of feature names to plot. If None, uses all available voltage features. Defaults to None.

  • title (str, optional) – Title for the figure. Defaults to “”.

Returns:

A tuple containing:
  • fig (matplotlib.figure.Figure): The figure object containing all histograms.

  • axs (np.ndarray): Array of matplotlib.axes.Axes objects for each subplot.

Return type:

tuple

Note

The function creates a 4x12 grid layout with histograms and colorbars. Each histogram uses quantile-based limits (0.1-0.9 for color range, 0.005-0.995 for histogram range) to handle outliers gracefully. The PuOr colormap is used for feature value coloring.