Skip to content

Plotting internals

These modules support the plotting package but are better treated as implementation details than as primary user entry points.

Defaults

soundscapy.plotting.defaults

Default parameters and constants for soundscape plotting functions.

This module provides common default values used for various plot types, including density plots, scatter plots, and styling parameters. It contains predefined color schemes, font settings, and layout configurations to ensure consistent visualization across the package.

Layers

soundscapy.plotting.layers

Layer-based visualization components for plotting.

This module provides a system of layer classes that implement different visualization techniques for ISO plots. Each layer encapsulates a specific visualization method and knows how to render itself on a given context.

CLASS DESCRIPTION
Layer

Base class for all visualization layers.

ScatterLayer

Layer for rendering scatter plots.

DensityLayer

Layer for rendering kernel density plots.

SimpleDensityLayer

Layer for rendering simplified density plots with fewer contour levels.

SPILayer

Layer for rendering SPI plots.

SPISimpleLayer

Layer for rendering simplified SPI plots with fewer contour levels.

SPIDensityLayer

Layer for rendering simplified SPI plots with fewer contour levels.

SPIScatterLayer

Layer for rendering simplified SPI plots with fewer contour levels.

Layer

Layer(
    custom_data: DataFrame | None = None,
    param_model: type[SeabornParams] = SeabornParams,
    **params: Any,
)

Base class for all visualization layers.

A Layer encapsulates a specific visualization technique and its associated parameters. Layers know how to render themselves onto a PlotContext's axes.

ATTRIBUTE DESCRIPTION
custom_data

Optional custom data for this specific layer, overriding context data

TYPE: DataFrame | None

params

Parameter model instance for this layer

TYPE: ParamModel

Initialize a Layer.

PARAMETER DESCRIPTION
custom_data

Optional custom data for this specific layer, overriding context data

TYPE: DataFrame | None DEFAULT: None

param_model

The parameter model class to use, if None uses a generic ParamModel

TYPE: type[SeabornParams] DEFAULT: SeabornParams

**params

Parameters for the layer

TYPE: Any DEFAULT: {}

METHOD DESCRIPTION
render

Render this layer on the given context.

Source code in src/soundscapy/plotting/layers.py
def __init__(
    self,
    custom_data: pd.DataFrame | None = None,
    param_model: type[SeabornParams] = SeabornParams,
    **params: Any,
) -> None:
    """
    Initialize a Layer.

    Parameters
    ----------
    custom_data
        Optional custom data for this specific layer, overriding context data
    param_model
        The parameter model class to use, if None uses a generic ParamModel
    **params
        Parameters for the layer

    """
    self.custom_data = custom_data
    # Create parameter model instance
    self.params = param_model(**params)
render
render(context: PlotContext) -> None

Render this layer on the given context.

PARAMETER DESCRIPTION
context

The context containing data and axes for rendering

TYPE: PlotContext

Source code in src/soundscapy/plotting/layers.py
def render(self, context: PlotContext) -> None:
    """
    Render this layer on the given context.

    Parameters
    ----------
    context
        The context containing data and axes for rendering

    """
    if context.ax is None:
        msg = "Cannot render layer: context has no associated axes"
        raise ValueError(msg)

    # Use custom data if provided, otherwise context data
    data = self.custom_data if self.custom_data is not None else context.data

    if data is None:
        msg = "No data available for rendering layer"
        raise ValueError(msg)

    self._render_implementation(data, context, context.ax)

ScatterLayer

ScatterLayer(
    custom_data: DataFrame | None = None, **params: Any
)

Bases: Layer

Layer for rendering scatter plots.

Initialize a ScatterLayer.

PARAMETER DESCRIPTION
custom_data

Optional custom data for this specific layer

TYPE: DataFrame | None DEFAULT: None

**params

Parameters for the scatter plot

TYPE: Any DEFAULT: {}

Source code in src/soundscapy/plotting/layers.py
def __init__(self, custom_data: pd.DataFrame | None = None, **params: Any) -> None:
    """
    Initialize a ScatterLayer.

    Parameters
    ----------
    custom_data
        Optional custom data for this specific layer
    **params
        Parameters for the scatter plot

    """
    super().__init__(custom_data=custom_data, param_model=ScatterParams, **params)

DensityLayer

DensityLayer(
    custom_data: DataFrame | None = None,
    *,
    param_model: type[DensityParams] = DensityParams,
    include_outline: bool = False,
    **params: Any,
)

Bases: Layer

Layer for rendering kernel density plots.

Initialize a DensityLayer.

PARAMETER DESCRIPTION
custom_data

Optional custom data for this specific layer

TYPE: DataFrame | None DEFAULT: None

include_outline

Whether to include an outline around the density plot

TYPE: bool DEFAULT: False

**params

Parameters for the density plot

TYPE: Any DEFAULT: {}

Source code in src/soundscapy/plotting/layers.py
def __init__(
    self,
    custom_data: pd.DataFrame | None = None,
    *,
    param_model: type[DensityParams] = DensityParams,
    include_outline: bool = False,
    **params: Any,
) -> None:
    """
    Initialize a DensityLayer.

    Parameters
    ----------
    custom_data
        Optional custom data for this specific layer
    include_outline
        Whether to include an outline around the density plot
    **params
        Parameters for the density plot

    """
    self.include_outline = include_outline
    self.params: DensityParams
    super().__init__(custom_data=custom_data, param_model=param_model, **params)

SimpleDensityLayer

SimpleDensityLayer(
    custom_data: DataFrame | None = None,
    *,
    include_outline: bool = True,
    param_model: type[
        SimpleDensityParams
    ] = SimpleDensityParams,
    **params: Any,
)

Bases: DensityLayer

Layer for rendering simplified density plots with fewer contour levels.

Initialize a SimpleDensityLayer.

PARAMETER DESCRIPTION
custom_data

Optional custom data for this specific layer

TYPE: DataFrame | None DEFAULT: None

include_outline

Whether to include an outline around the density plot

TYPE: bool DEFAULT: True

**params

Parameters for the density plot

TYPE: Any DEFAULT: {}

Source code in src/soundscapy/plotting/layers.py
def __init__(
    self,
    custom_data: pd.DataFrame | None = None,
    *,
    include_outline: bool = True,
    param_model: type[SimpleDensityParams] = SimpleDensityParams,
    **params: Any,
) -> None:
    """
    Initialize a SimpleDensityLayer.

    Parameters
    ----------
    custom_data
        Optional custom data for this specific layer
    include_outline
        Whether to include an outline around the density plot
    **params
        Parameters for the density plot

    """
    super().__init__(
        custom_data=custom_data,
        include_outline=include_outline,  # Could move into params now
        param_model=param_model,
        **params,
    )

SPILayer

SPILayer(
    spi_target_data: DataFrame | ndarray | None = None,
    *,
    msn_params: DirectParams | CentredParams | None = None,
    n: int = 10000,
    param_model: type[SPISeabornParams] = SPISeabornParams,
    **params: Any,
)

Bases: Layer

Layer for rendering SPI plots.

Initialize an SPILayer.

PARAMETER DESCRIPTION
spi_target_data

Pre-sampled data for SPI target distribution. When None, msn_params must be provided.

TYPE: DataFrame | ndarray | None DEFAULT: None

msn_params

Parameters to generate SPI data if no spi_target_data is provided

TYPE: DirectParams | CentredParams | None DEFAULT: None

n

Number of samples to generate if using msn_params

TYPE: int DEFAULT: 10000

param_model

The parameter model class to use

TYPE: type[SPISeabornParams] DEFAULT: SPISeabornParams

**params

Parameters for the layer. For compatibility with other layers, if 'custom_data' is present and spi_target_data is None, custom_data will be used as the SPI target data.

TYPE: Any DEFAULT: {}

Notes

Either spi_target_data or msn_params must be provided, but not both. The test data for SPI calculations will be retrieved from the plot context.

METHOD DESCRIPTION
render

Render this layer on the given context.

show_score

Show the SPI score on the plot.

Source code in src/soundscapy/plotting/layers.py
def __init__(
    self,
    spi_target_data: pd.DataFrame | np.ndarray | None = None,
    *,
    # TODO(MitchellAcoustics): Allow passing raw param values,
    #  not just Param objects
    msn_params: DirectParams | CentredParams | None = None,
    n: int = 10000,
    param_model: type[SPISeabornParams] = SPISeabornParams,
    **params: Any,
) -> None:
    """
    Initialize an SPILayer.

    Parameters
    ----------
    spi_target_data
        Pre-sampled data for SPI target distribution.
        When None, msn_params must be provided.
    msn_params
        Parameters to generate SPI data if no spi_target_data is provided
    n
        Number of samples to generate if using msn_params
    param_model
        The parameter model class to use
    **params
        Parameters for the layer. For compatibility with other layers,
        if 'custom_data' is present and spi_target_data is None,
        custom_data will be used as the SPI target data.

    Notes
    -----
    Either spi_target_data or msn_params must be provided, but not both.
    The test data for SPI calculations will be retrieved from the plot context.

    """
    # The custom_data passed when adding this layer should be the spi_data.
    # We will retrieve the test_data from the subplot context, so real data layers
    # need to be passed before this one, or use the data from the
    # main ISOPlot context
    custom_data = params.pop("custom_data", None)
    if custom_data is not None and spi_target_data is None:
        logger.warning(
            "`spi_target_data` not found, but `custom_data` was found. "
            "Using `custom_data` as the SPI target data. "
            "\nNote: Passing the SPI data to `spi_target_data` is preferred."
        )
        spi_target_data = custom_data

    # Check that we have the information needed to generate SPI target data
    # (either the spi_data or msn_params)
    spi_target_data, self.spi_params = self._validate_spi_inputs(
        spi_target_data, msn_params
    )
    # Generate the spi target data
    self.spi_data: pd.DataFrame = self._generate_spi_data(
        spi_target_data, self.spi_params, n
    )
    params["n"] = n
    self.params: SPISeabornParams

    super().__init__(custom_data=self.spi_data, param_model=param_model, **params)
render
render(context: PlotContext) -> None

Render this layer on the given context.

PARAMETER DESCRIPTION
context

The context containing data and axes for rendering

TYPE: PlotContext

Source code in src/soundscapy/plotting/layers.py
def render(self, context: PlotContext) -> None:
    """
    Render this layer on the given context.

    Parameters
    ----------
    context
        The context containing data and axes for rendering

    """
    if context.ax is None:
        msg = "Cannot render layer: context has no associated axes"
        raise ValueError(msg)

    target_data = self.spi_data
    # Mutate spi_data to match the context test_data.
    target_data = self._process_spi_data(target_data, context)

    if target_data is None:
        msg = "No data available for rendering layer"
        raise ValueError(msg)

    # Now we have the SPI target_data and the test data in context.data
    # SPILayer._render_implementation() will handle calculating the SPI score
    # against this particular context / ax test data

    self._render_implementation(target_data, context, context.ax)
show_score
show_score(
    spi_sc: int | None,
    show_score: Literal["on axis", "under title"],
    context: PlotContext,
    ax: Axes,
    axis_text_kwargs: dict[str, Any],
) -> None

Show the SPI score on the plot.

PARAMETER DESCRIPTION
spi_sc

The SPI score to show

TYPE: int | None

show_score

Where to show the score

TYPE: Literal['on axis', 'under title']

context

The context containing data and axes for rendering

TYPE: PlotContext

ax

The axes to render the score on

TYPE: Axes

axis_text_kwargs

Additional arguments for the axis text

TYPE: dict[str, Any]

Source code in src/soundscapy/plotting/layers.py
def show_score(
    self,
    spi_sc: int | None,
    show_score: Literal["on axis", "under title"],
    context: PlotContext,
    ax: Axes,
    axis_text_kwargs: dict[str, Any],
) -> None:
    """
    Show the SPI score on the plot.

    Parameters
    ----------
    spi_sc
        The SPI score to show
    show_score
        Where to show the score
    context
        The context containing data and axes for rendering
    ax
        The axes to render the score on
    axis_text_kwargs
        Additional arguments for the axis text

    """
    if spi_sc is not None:
        if show_score == "on axis":
            self._add_score_as_text(
                ax=ax,
                spi_sc=spi_sc,
                **axis_text_kwargs,
            )
        elif show_score == "under title":
            self._add_score_under_title(
                context=context,
                ax=ax,
                spi_sc=spi_sc,
            )

SPISimpleLayer

SPISimpleLayer(
    spi_target_data: DataFrame | ndarray | None = None,
    *,
    msn_params: DirectParams | CentredParams | None = None,
    include_outline: bool = True,
    **params: Any,
)

Bases: SPILayer, SimpleDensityLayer

Layer for rendering simplified SPI plots with fewer contour levels.

Initialize an SPISimpleLayer.

PARAMETER DESCRIPTION
spi_target_data

Optional SPI target data for this specific layer

TYPE: DataFrame | ndarray | None DEFAULT: None

msn_params

Parameters to generate SPI data if no custom data is provided

TYPE: DirectParams | CentredParams | None DEFAULT: None

include_outline

Whether to include an outline around the density plot

TYPE: bool DEFAULT: True

**params

Parameters for the density plot

TYPE: Any DEFAULT: {}

Source code in src/soundscapy/plotting/layers.py
def __init__(
    self,
    spi_target_data: pd.DataFrame | np.ndarray | None = None,
    *,
    msn_params: DirectParams | CentredParams | None = None,
    include_outline: bool = True,
    **params: Any,
) -> None:
    """
    Initialize an SPISimpleLayer.

    Parameters
    ----------
    spi_target_data
        Optional SPI target data for this specific layer
    msn_params
        Parameters to generate SPI data if no custom data is provided
    include_outline
        Whether to include an outline around the density plot
    **params
        Parameters for the density plot

    """
    self.params: SPISimpleDensityParams
    super().__init__(
        spi_target_data=spi_target_data,
        include_outline=include_outline,
        param_model=SPISimpleDensityParams,
        msn_params=msn_params,
        **params,
    )

SPIDensityLayer

SPIDensityLayer()

Bases: SPILayer, DensityLayer

Layer for rendering simplified SPI plots with fewer contour levels.

Initialize SPIDensityLayer.

This initialization is not supported and will raise NotImplementedError. Use SPISimpleLayer instead.

Source code in src/soundscapy/plotting/layers.py
def __init__(self) -> None:
    """
    Initialize SPIDensityLayer.

    This initialization is not supported and will raise NotImplementedError.
    Use SPISimpleLayer instead.
    """
    msg = (
        "Only the simple density layer type is currently supported for SPI plots. "
        "Please use SPISimpleLayer"
    )
    raise NotImplementedError(msg)

SPIScatterLayer

SPIScatterLayer()

Bases: SPILayer, ScatterLayer

Layer for rendering simplified SPI plots with fewer contour levels.

Initialize SPIScatterLayer.

This initialization is not supported and will raise NotImplementedError. Use SPISimpleLayer instead.

Source code in src/soundscapy/plotting/layers.py
def __init__(self) -> None:
    """
    Initialize SPIScatterLayer.

    This initialization is not supported and will raise NotImplementedError.
    Use SPISimpleLayer instead.
    """
    msg = (
        "Only the simple density layer type is currently supported for SPI plots. "
        "Please use SPISimpleLayer"
    )
    raise NotImplementedError(msg)

Parameter models

soundscapy.plotting.param_models

Parameter models for plotting functions in soundscapy.

This module provides parameter validation and management classes for various plotting functions using Pydantic dataclasses. The module includes:

  • Base ParamModel class with common functionality
  • SeabornParams for seaborn plotting parameters
  • Specialized parameter classes for different plot types
  • Style and subplot configuration classes

The parameter models provide:

  • Type validation and conversion
  • Default value management
  • Parameter updating with validation
  • Dictionary-style access to parameters
  • Deep copying functionality
CLASS DESCRIPTION
ParamModel

Base model for parameter validation using dataclasses.

SeabornParams

Base parameters for seaborn plotting functions.

ScatterParams

Parameters for scatter plot functions.

DensityParams

Parameters for density plot functions.

SimpleDensityParams

Parameters for simple density plot functions.

SPISeabornParams

Base parameters for SPI (Soundscape Perceptual Index) seaborn plotting functions.

SPISimpleDensityParams

Parameters for SPI simple density plot functions.

JointPlotParams

Parameters for joint plot functions.

StyleParams

Parameters for plot styling.

SubplotsParams

Parameters for subplots.

ParamModel

Base model for parameter validation using dataclasses.

This class provides the foundation for all parameter models with common configuration settings and utility methods.

METHOD DESCRIPTION
__post_init__

Process extra fields after initialization.

update

Update the attributes of the instance based on the provided parameters.

get_defaults

Get the default values for all defined fields in the model.

get

Get a parameter value with a default fallback.

__getitem__

Get a parameter value using dictionary-style access.

as_dict

Get all parameters as a dictionary.

copy

Create a deep copy of the parameter model instance.

model_copy

Create a copy of the parameter model instance.

get_changed_params

Get parameters that have been changed from their defaults.

get_multiple

Get multiple parameters as a dictionary.

pop

Remove a parameter and return its value.

drop

Remove a parameter without returning its value.

ATTRIBUTE DESCRIPTION
defaults

Property to access default field values.

TYPE: dict[str, Any]

defined_field_names

Get the names of all fields defined for the model.

TYPE: list[str]

current_field_names

Get the names of all current fields.

TYPE: list[str]

defaults property
defaults: dict[str, Any]

Property to access default field values.

RETURNS DESCRIPTION
dict[str, Any]

Dictionary mapping field names to their default values.

defined_field_names property
defined_field_names: list[str]

Get the names of all fields defined for the model.

RETURNS DESCRIPTION
list[str]

List of field names

current_field_names property
current_field_names: list[str]

Get the names of all current fields.

RETURNS DESCRIPTION
list[str]

List of field names

__post_init__
__post_init__() -> None

Process extra fields after initialization.

Source code in src/soundscapy/plotting/param_models.py
def __post_init__(self) -> None:
    """Process extra fields after initialization."""
    # Move any extra fields to _extra_fields
    for key, value in list(self.__dict__.items()):
        if key not in self.defined_field_names:
            setattr(self, key, value)
update
update(
    *,
    extra: Literal["allow", "forbid", "ignore"] = "allow",
    ignore_null: bool = True,
    **kwargs: Any,
) -> None

Update the attributes of the instance based on the provided parameters.

PARAMETER DESCRIPTION
extra

Determines how to handle extra fields in kwargs.

TYPE: Literal['allow', 'forbid', 'ignore'] DEFAULT: 'allow'

ignore_null

If True, removes None values from kwargs.

TYPE: bool DEFAULT: True

**kwargs

Field names and values to be updated.

TYPE: Any DEFAULT: {}

Source code in src/soundscapy/plotting/param_models.py
@validate_call
def update(
    self,
    *,
    extra: Literal["allow", "forbid", "ignore"] = "allow",
    ignore_null: bool = True,
    **kwargs: Any,
) -> None:
    """
    Update the attributes of the instance based on the provided parameters.

    Parameters
    ----------
    extra
        Determines how to handle extra fields in `kwargs`.
    ignore_null
        If True, removes `None` values from `kwargs`.
    **kwargs
        Field names and values to be updated.

    """
    # Create a copy of kwargs to avoid modifying it during iteration
    update_kwargs = kwargs.copy()

    if extra == "forbid":
        # Forbid extra fields
        unknown_keys = set(update_kwargs) - set(self.defined_field_names)
        if unknown_keys:
            msg = f"Unknown parameters: {unknown_keys}"
            raise ValueError(msg)
    elif extra == "ignore":
        # Ignore extra fields
        update_kwargs = {
            k: v for k, v in update_kwargs.items() if k in self.defined_field_names
        }

    # Remove None values if ignore_null is True
    if ignore_null:
        update_kwargs = {k: v for k, v in update_kwargs.items() if v is not None}

    # Update fields
    for key, value in update_kwargs.items():
        if key in self.defined_field_names or extra == "allow":
            setattr(self, key, value)
get_defaults
get_defaults() -> dict[str, Any]

Get the default values for all defined fields in the model.

RETURNS DESCRIPTION
dict[str, Any]

Dictionary mapping field names to their default values. Excludes the special _extra_fields field.

Source code in src/soundscapy/plotting/param_models.py
def get_defaults(self) -> dict[str, Any]:
    """
    Get the default values for all defined fields in the model.

    Returns
    -------
    :
        Dictionary mapping field names to their default values.
        Excludes the special `_extra_fields` field.

    """
    return {
        fld.name: fld.default for fld in fields(self) if fld.name != "_extra_fields"
    }
get
get(key: str, default: Any = None) -> Any

Get a parameter value with a default fallback.

PARAMETER DESCRIPTION
key

Name of the parameter

TYPE: str

default

Default value if parameter doesn't exist

TYPE: Any DEFAULT: None

RETURNS DESCRIPTION
Any

Parameter value or default

Source code in src/soundscapy/plotting/param_models.py
def get(self, key: str, default: Any = None) -> Any:
    """
    Get a parameter value with a default fallback.

    Parameters
    ----------
    key
        Name of the parameter
    default
        Default value if parameter doesn't exist

    Returns
    -------
    :
        Parameter value or default

    """
    if key in self.current_field_names:
        return getattr(self, key)
    return default
__getitem__
__getitem__(key: str) -> Any

Get a parameter value using dictionary-style access.

PARAMETER DESCRIPTION
key

Name of the parameter

TYPE: str

RETURNS DESCRIPTION
Any

Parameter value

RAISES DESCRIPTION
KeyError

If the parameter doesn't exist

Source code in src/soundscapy/plotting/param_models.py
def __getitem__(self, key: str) -> Any:
    """
    Get a parameter value using dictionary-style access.

    Parameters
    ----------
    key
        Name of the parameter

    Returns
    -------
    :
        Parameter value

    Raises
    ------
    KeyError
        If the parameter doesn't exist

    """
    if key in self.current_field_names:
        return getattr(self, key)
    msg = f"Parameter '{key}' does not exist."
    raise KeyError(msg)
as_dict
as_dict(drop: list[str] | None = None) -> dict[str, Any]

Get all parameters as a dictionary.

RETURNS DESCRIPTION
dict[str, Any]

Dictionary of parameter values

Source code in src/soundscapy/plotting/param_models.py
def as_dict(self, drop: list[str] | None = None) -> dict[str, Any]:
    """
    Get all parameters as a dictionary.

    Returns
    -------
    :
        Dictionary of parameter values

    """
    dictionary = self.__dict__.copy()
    if drop is not None:
        for key in drop:
            dictionary.pop(key, None)
    return dictionary
copy
copy() -> ParamModel

Create a deep copy of the parameter model instance.

RETURNS DESCRIPTION
ParamModel

A deep copy of the current instance with all nested objects copied.

Source code in src/soundscapy/plotting/param_models.py
def copy(self) -> ParamModel:
    """
    Create a deep copy of the parameter model instance.

    Returns
    -------
    :
        A deep copy of the current instance with all nested objects copied.

    """
    return copy.deepcopy(self)
model_copy
model_copy() -> ParamModel

Create a copy of the parameter model instance.

Deprecated

This method is deprecated. Use :meth:copy instead. Kept only for backwards compatibility with Pydantic.

RETURNS DESCRIPTION
ParamModel

A deep copy of the current instance.

Source code in src/soundscapy/plotting/param_models.py
def model_copy(self) -> ParamModel:
    """
    Create a copy of the parameter model instance.

    !!! warning "Deprecated"
        This method is deprecated. Use :meth:`copy` instead.
        Kept only for backwards compatibility with Pydantic.

    Returns
    -------
    :
        A deep copy of the current instance.

    """
    warnings.warn(
        "model_copy is deprecated. Use copy instead."
        "Kept only for backwards compatibility with Pydantic.",
        DeprecationWarning,
        stacklevel=2,
    )
    return self.copy()
get_changed_params
get_changed_params() -> dict[str, Any]

Get parameters that have been changed from their defaults.

This method compares the current parameter values against the default values and returns a dictionary containing only the parameters that differ from their defaults.

RETURNS DESCRIPTION
dict[str, Any]

Dictionary of changed parameters and their current values.

Source code in src/soundscapy/plotting/param_models.py
def get_changed_params(self) -> dict[str, Any]:
    """
    Get parameters that have been changed from their defaults.

    This method compares the current parameter values against the default values
    and returns a dictionary containing only the parameters that differ from
    their defaults.

    Returns
    -------
    :
        Dictionary of changed parameters and their current values.

    """
    default_values = self.get_defaults()
    current_values = self.as_dict()

    # Use dictionary comprehension to identify and collect changed parameters
    # Return the current values (not default values) for the changed parameters
    return {
        param_name: current_values[param_name]
        for param_name, default_value in default_values.items()
        if current_values[param_name] != default_value
    }
get_multiple
get_multiple(keys: list[str]) -> dict[str, Any]

Get multiple parameters as a dictionary.

PARAMETER DESCRIPTION
keys

List of parameter names

TYPE: list[str]

RETURNS DESCRIPTION
dict[str, Any]

Dictionary of parameter values

Source code in src/soundscapy/plotting/param_models.py
def get_multiple(self, keys: list[str]) -> dict[str, Any]:
    """
    Get multiple parameters as a dictionary.

    Parameters
    ----------
    keys
        List of parameter names

    Returns
    -------
    :
        Dictionary of parameter values

    """
    return {key: self[key] for key in keys if key in self.current_field_names}
pop
pop(key: str) -> Any

Remove a parameter and return its value.

For fields defined in the model, the value is reset to its default.

PARAMETER DESCRIPTION
key

Name of the parameter

TYPE: str

RETURNS DESCRIPTION
Any

Value of the removed parameter

RAISES DESCRIPTION
KeyError

If the parameter doesn't exist

Source code in src/soundscapy/plotting/param_models.py
def pop(self, key: str) -> Any:
    """
    Remove a parameter and return its value.

    For fields defined in the model, the value is reset to its default.

    Parameters
    ----------
    key
        Name of the parameter

    Returns
    -------
    :
        Value of the removed parameter

    Raises
    ------
    KeyError
        If the parameter doesn't exist

    """
    if key in self.defaults:
        value = getattr(self, key)
        setattr(self, key, self.defaults[key])  # Reset to default/None
        return value
    if key in self.current_field_names:
        value = self.get(key)
        delattr(self, key)
        return value
    msg = f"Parameter '{key}' does not exist."
    raise KeyError(msg)
drop
drop(
    keys: str | Iterable[str],
    *,
    ignore_missing: bool = True,
) -> None

Remove a parameter without returning its value.

PARAMETER DESCRIPTION
keys

Name of the parameter or list of parameters

TYPE: str | Iterable[str]

ignore_missing

If True, ignore missing keys. If False, raise KeyError for missing keys.

TYPE: bool DEFAULT: True

Source code in src/soundscapy/plotting/param_models.py
def drop(self, keys: str | Iterable[str], *, ignore_missing: bool = True) -> None:
    """
    Remove a parameter without returning its value.

    Parameters
    ----------
    keys
        Name of the parameter or list of parameters
    ignore_missing
        If True, ignore missing keys. If False, raise KeyError for missing keys.

    """
    if isinstance(keys, str):
        keys = [keys]

    for key in keys:
        try:
            delattr(self, key)
        except (KeyError, AttributeError) as e:
            if not ignore_missing:
                if isinstance(e, AttributeError):
                    msg = f"Parameter '{key}' does not exist."
                    raise KeyError(msg) from e
                raise

SeabornParams

Bases: ParamModel

Base parameters for seaborn plotting functions.

Provides common parameters used across seaborn plotting functions including data source, aesthetic mappings, and color settings.

METHOD DESCRIPTION
crosscheck_palette_hue

Check if the palette is valid for the given hue.

as_seaborn_kwargs

Convert parameters to kwargs compatible with seaborn functions.

crosscheck_palette_hue
crosscheck_palette_hue() -> None

Check if the palette is valid for the given hue.

This method ensures that palette is only used when hue is provided.

Source code in src/soundscapy/plotting/param_models.py
def crosscheck_palette_hue(self) -> None:
    """
    Check if the palette is valid for the given hue.

    This method ensures that palette is only used when hue is provided.
    """
    self.palette = self.palette if self.hue is not None else None
as_seaborn_kwargs
as_seaborn_kwargs(
    drop: list[str] | None = None,
) -> dict[str, Any]

Convert parameters to kwargs compatible with seaborn functions.

RETURNS DESCRIPTION
dict[str, Any]

Dictionary of parameter values suitable for seaborn plotting functions.

Source code in src/soundscapy/plotting/param_models.py
def as_seaborn_kwargs(self, drop: list[str] | None = None) -> dict[str, Any]:
    """
    Convert parameters to kwargs compatible with seaborn functions.

    Returns
    -------
    :
        Dictionary of parameter values suitable for seaborn plotting functions.

    """
    return self.as_dict(drop=drop)

ScatterParams

Bases: SeabornParams

Parameters for scatter plot functions.

Inherits from SeabornParams and adds scatter-specific parameters.

DensityParams

Bases: SeabornParams

Parameters for density plot functions.

Inherits from SeabornParams and adds density-specific parameters for contour plots and kernel density estimation.

METHOD DESCRIPTION
as_seaborn_kwargs

Convert parameters to kwargs compatible with seaborn functions.

to_outline

Convert to outline parameters.

as_seaborn_kwargs
as_seaborn_kwargs(
    drop: list[str] | None = None,
) -> dict[str, Any]

Convert parameters to kwargs compatible with seaborn functions.

RETURNS DESCRIPTION
dict[str, Any]

Dictionary of parameter values suitable for seaborn plotting functions.

Source code in src/soundscapy/plotting/param_models.py
def as_seaborn_kwargs(self, drop: list[str] | None = None) -> dict[str, Any]:
    """
    Convert parameters to kwargs compatible with seaborn functions.

    Returns
    -------
    :
        Dictionary of parameter values suitable for seaborn plotting functions.

    """
    # None to drop yet
    if drop is None:
        drop = []
    # Add common parameters to drop list
    drop.extend(["incl_outline"])
    return super().as_seaborn_kwargs(drop=drop)
to_outline
to_outline(
    *, alpha: float = 1, fill: bool = False
) -> DensityParams

Convert to outline parameters.

PARAMETER DESCRIPTION
alpha

Alpha value for the outline.

TYPE: float DEFAULT: 1

fill

Whether to fill the outline.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
DensityParams

New instance with outline parameters.

Source code in src/soundscapy/plotting/param_models.py
def to_outline(self, *, alpha: float = 1, fill: bool = False) -> DensityParams:
    """
    Convert to outline parameters.

    Parameters
    ----------
    alpha
        Alpha value for the outline.
    fill
        Whether to fill the outline.

    Returns
    -------
    :
        New instance with outline parameters.

    """
    # Create a copy of the parameters
    params_dict = self.as_dict()

    # Update parameters for outline
    params_dict.update(alpha=alpha, fill=fill, legend=False)

    # Create a new instance with the updated parameters
    return DensityParams(**params_dict)

SimpleDensityParams

Bases: DensityParams

Parameters for simple density plot functions.

Inherits from DensityParams with overridden defaults for simplified density plots with fewer contour levels.

SPISeabornParams

Bases: SeabornParams

Base parameters for SPI (Soundscape Perceptual Index) seaborn plotting functions.

Specialized parameters for plotting SPI data with specific styling and annotation options.

METHOD DESCRIPTION
as_seaborn_kwargs

Convert parameters to kwargs compatible with seaborn functions.

as_seaborn_kwargs
as_seaborn_kwargs(
    drop: list[str] | None = None,
) -> dict[str, Any]

Convert parameters to kwargs compatible with seaborn functions.

RETURNS DESCRIPTION
dict[str, Any]

Dictionary of parameter values suitable for seaborn plotting functions.

Source code in src/soundscapy/plotting/param_models.py
def as_seaborn_kwargs(self, drop: list[str] | None = None) -> dict[str, Any]:
    """
    Convert parameters to kwargs compatible with seaborn functions.

    Returns
    -------
    :
        Dictionary of parameter values suitable for seaborn plotting functions.

    """
    droplist = ["n", "show_score", "axis_text_kw"]
    if isinstance(drop, list):
        droplist.extend(drop)
    return self.as_dict(drop=droplist)

SPISimpleDensityParams

Bases: SPISeabornParams, SimpleDensityParams

Parameters for SPI simple density plot functions.

Combines SPI-specific parameters with simple density plot parameters through multiple inheritance.

JointPlotParams

Bases: ParamModel

Parameters for joint plot functions.

Parameters for creating joint plots that show both the relationship between two variables and their individual distributions.

StyleParams

Bases: ParamModel

Parameters for plot styling.

Controls the visual appearance of plots including axes limits, labels, lines, and text formatting.

SubplotsParams

Bases: ParamModel

Parameters for subplots.

Controls the layout and configuration of subplot grids, including figure size, sharing of axes, and automatic allocation.

METHOD DESCRIPTION
as_plt_subplots_args

Pass matplotlib subplot arguments to a plt.subplots call.

ATTRIBUTE DESCRIPTION
n_subplots_by

"The number of subplots allocated for each subplot_by category.

TYPE: int

n_subplots

Get the number of subplots.

TYPE: int

n_subplots_by class-attribute instance-attribute
n_subplots_by: int = -1

"The number of subplots allocated for each subplot_by category.

n_subplots property
n_subplots: int

Get the number of subplots.

RETURNS DESCRIPTION
int

Number of subplots

as_plt_subplots_args
as_plt_subplots_args() -> dict[str, Any]

Pass matplotlib subplot arguments to a plt.subplots call.

RETURNS DESCRIPTION
dict[str, Any]

Dictionary of subplot parameters.

Source code in src/soundscapy/plotting/param_models.py
def as_plt_subplots_args(self) -> dict[str, Any]:
    """
    Pass matplotlib subplot arguments to a plt.subplots call.

    Returns
    -------
    :
        Dictionary of subplot parameters.

    """
    kwargs = self.as_dict()
    for key in [
        "subplot_by",
        "n_subplots_by",
        "auto_allocate_axes",
        "adjust_figsize",
    ]:
        kwargs.pop(key, None)
    return kwargs

Plot context

soundscapy.plotting.plot_context

Data and state management for plotting layers.

This module provides the PlotContext class that manages data and state for ISOPlot visualizations, enabling a more flexible architecture for plot generation with support for layered visualizations and subplot management.

CLASS DESCRIPTION
PlotContext

Manages data and state for a plot or subplot.

PlotContext

PlotContext(
    data: DataFrame | None = None,
    x: str = "ISOPleasant",
    y: str = "ISOEventful",
    hue: str | None = None,
    ax: Axes | None = None,
    title: str | None = None,
)

Manages data and state for a plot or subplot.

This class centralizes the management of data, coordinates, and other state needed for rendering plot layers, allowing for consistent data access patterns and simplified layer implementation.

ATTRIBUTE DESCRIPTION
data

The data associated with this context

x

The column name for x-axis data

y

The column name for y-axis data

hue

The column name for color encoding, if any

ax

The matplotlib Axes object this context is associated with

title

The title for this context's plot

layers

The visualization layers to be rendered on this context

TYPE: list[Layer]

Initialize a PlotContext.

PARAMETER DESCRIPTION
data

Data to be visualized

TYPE: DataFrame | None DEFAULT: None

x

Column name for x-axis data

TYPE: str DEFAULT: 'ISOPleasant'

y

Column name for y-axis data

TYPE: str DEFAULT: 'ISOEventful'

hue

Column name for color encoding

TYPE: str | None DEFAULT: None

ax

Matplotlib axis to render on

TYPE: Axes | None DEFAULT: None

title

Title for this plot context

TYPE: str | None DEFAULT: None

METHOD DESCRIPTION
create_child

Create a child context that inherits properties from this context.

Source code in src/soundscapy/plotting/plot_context.py
def __init__(
    self,
    data: pd.DataFrame | None = None,
    x: str = "ISOPleasant",
    y: str = "ISOEventful",
    hue: str | None = None,
    ax: Axes | None = None,
    title: str | None = None,
) -> None:
    """
    Initialize a PlotContext.

    Parameters
    ----------
    data
        Data to be visualized
    x
        Column name for x-axis data
    y
        Column name for y-axis data
    hue
        Column name for color encoding
    ax
        Matplotlib axis to render on
    title
        Title for this plot context

    """
    self.data = data
    self.x = x
    self.y = y
    self.hue = hue
    self.ax = ax
    self.title = title
    self.layers: list[Layer] = []
    self.parent: PlotContext | None = None
create_child
create_child(
    data: DataFrame | None = None,
    title: str | None = None,
    ax: Axes | None = None,
) -> PlotContext

Create a child context that inherits properties from this context.

PARAMETER DESCRIPTION
data

Data for the child context. If None, inherits from parent.

TYPE: DataFrame | None DEFAULT: None

title

Title for the child context

TYPE: str | None DEFAULT: None

ax

Matplotlib axis for the child context

TYPE: Axes | None DEFAULT: None

RETURNS DESCRIPTION
PlotContext

A new child context with inherited properties

Source code in src/soundscapy/plotting/plot_context.py
def create_child(
    self,
    data: pd.DataFrame | None = None,
    title: str | None = None,
    ax: Axes | None = None,
) -> PlotContext:
    """
    Create a child context that inherits properties from this context.

    Parameters
    ----------
    data
        Data for the child context. If None, inherits from parent.
    title
        Title for the child context
    ax
        Matplotlib axis for the child context

    Returns
    -------
    :
        A new child context with inherited properties

    """
    child = PlotContext(
        data=data if data is not None else self.data,
        x=self.x,
        y=self.y,
        hue=self.hue,
        ax=ax,
        title=title,
    )
    child.parent = self
    return child

Deprecated backends

soundscapy.plotting.backends_deprecated

Deprecation warnings for v0.7 APIs.

CLASS DESCRIPTION
CircumplexPlot

Alias for v0.7 API to raise deprecation warnings.

CircumplexPlotParams

Alias for v0.7 API to raise deprecation warnings.

Backend

Alias for v0.7 API to raise deprecation warnings.

PlotType

Alias for v0.7 API to raise deprecation warnings.

StyleOptions

Alias for v0.7 API to raise deprecation warnings.

CircumplexPlot

CircumplexPlot(*args, **kwargs)

Alias for v0.7 API to raise deprecation warnings.

Source code in src/soundscapy/plotting/backends_deprecated.py
def __init__(self, *args, **kwargs) -> None:
    msg = (
        "The v0.7 APIs are deprecated. Please update your code accordingly."
        "CircumplexPlot is deprecated. Use ISOPlot instead."
    )
    raise DeprecationWarning(
        msg,
    )

CircumplexPlotParams

CircumplexPlotParams(*args, **kwargs)

Alias for v0.7 API to raise deprecation warnings.

Source code in src/soundscapy/plotting/backends_deprecated.py
def __init__(self, *args, **kwargs) -> None:
    msg = (
        "The v0.7 APIs are deprecated. Please update your code accordingly."
        "CircumplexPlot is deprecated. Use ISOPlot instead."
    )
    raise DeprecationWarning(
        msg,
    )

Backend

Bases: Enum

Alias for v0.7 API to raise deprecation warnings.

PlotType

Alias for v0.7 API to raise deprecation warnings.

StyleOptions

StyleOptions(*args, **kwargs)

Alias for v0.7 API to raise deprecation warnings.

Source code in src/soundscapy/plotting/backends_deprecated.py
def __init__(self, *args, **kwargs) -> None:
    warnings.warn(
        "The v0.7 APIs are deprecated. Please update your code accordingly."
        "Backend is deprecated. Use ISOPlot instead.",
        DeprecationWarning,
        stacklevel=2,
    )