Skip to content

ISOPlot Interface

Main module for creating circumplex plots using different backends.

Examples:

>>> from soundscapy import isd, surveys
>>> from soundscapy.plotting.iso_plot import ISOPlot
>>> df = isd.load()
>>> df = surveys.add_iso_coords(df)
>>> sub_df = isd.select_location_ids(df, ['CamdenTown', 'RegentsParkJapan'])
>>> isoplot = (
...    ISOPlot(data=sub_df, hue="SessionID")
...    .create_subplots(
...        subplot_by="LocationID",
...        auto_allocate_axes=True,
...        adjust_figsize=True
...    )
...    .add_scatter()
...    .add_simple_density(fill=False)
...    .style()
... )
>>> isoplot.show() # xdoctest: +SKIP
CLASS DESCRIPTION
ExperimentalWarning

A warning class to signify experimental features.

ISOPlot

A class for creating circumplex plots using different backends.

ExperimentalWarning

Bases: Warning

A warning class to signify experimental features.

ISOPlot

ISOPlot(data=None, x='ISOPleasant', y='ISOEventful', title='Soundscape Density Plot', hue=None, palette='colorblind', figure=None, axes=None)

A class for creating circumplex plots using different backends.

This class provides methods for creating scatter plots and density plots based on the circumplex model of soundscape perception.

Examples:

>>> from soundscapy import isd, surveys
>>> df = isd.load()
>>> df = surveys.add_iso_coords(df)
>>> ct = isd.select_location_ids(df, ["CamdenTown", "RegentsParkJapan"])
>>> cp = (ISOPlot(ct, hue="LocationID")
...         .create_subplots()
...         .add_scatter()
...         .add_density()
...         .style())
>>> cp.show() # xdoctest: +SKIP

Initialize a ISOPlot instance.

PARAMETER DESCRIPTION
data

The data to be plotted, by default None

TYPE: DataFrame | None DEFAULT: None

x

Column name or data for x-axis, by default "ISOPleasant"

TYPE: str | ndarray | Series | None DEFAULT: 'ISOPleasant'

y

Column name or data for y-axis, by default "ISOEventful"

TYPE: str | ndarray | Series | None DEFAULT: 'ISOEventful'

title

Title of the plot, by default "Soundscape Density Plot"

TYPE: str | None DEFAULT: 'Soundscape Density Plot'

hue

Column name for color encoding, by default None

TYPE: str | None DEFAULT: None

palette

Color palette to use, by default "colorblind"

TYPE: SeabornPaletteType | None DEFAULT: 'colorblind'

figure

Existing figure to plot on, by default None

TYPE: Figure | SubFigure | None DEFAULT: None

axes

Existing axes to plot on, by default None

TYPE: Axes | ndarray | None DEFAULT: None

Examples:

Create a plot with default parameters:

>>> import pandas as pd
>>> import numpy as np
>>> rng = np.random.default_rng(42)
>>> data = pd.DataFrame(
...    rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
...    columns=['ISOPleasant', 'ISOEventful']
... )
>>> plot = ISOPlot()
>>> isinstance(plot, ISOPlot)
True

Create a plot with a DataFrame:

>>> data = pd.DataFrame(
...    np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
...          rng.integers(1, 3, 100)],
...    columns=['ISOPleasant', 'ISOEventful', 'Group'])
>>> plot = ISOPlot(data=data, hue='Group')
>>> plot.hue
'Group'

Create a plot directly with arrays:

>>> x, y = rng.multivariate_normal([0, 0], [[1, 0], [0, 1]], 100).T
>>> plot = ISOPlot(x=x, y=y)
>>> isinstance(plot, ISOPlot)
True
METHOD DESCRIPTION
add_annotation

Add an annotation to the plot.

add_density

Add a density layer to specific subplot(s).

add_layer

Add a visualization layer, optionally targeting specific subplot(s).

add_scatter

Add a scatter layer to specific subplot(s).

add_simple_density

Add a simple density layer to specific subplot(s).

add_spi

Add a SPI layer to specific subplot(s).

close

Close the figure.

create_subplots

Create subplots for the circumplex plot.

get_axes

Get the axes object.

get_figure

Get the figure object.

get_single_axes

Get a specific axes object.

savefig

Save the figure.

show

Show the figure.

style

Apply styling to the plot.

yield_axes_objects

Generate a sequence of axes objects to iterate over.

ATTRIBUTE DESCRIPTION
hue

Get the hue column name.

TYPE: str | None

title

Get the plot title.

TYPE: str | None

x

Get the x-axis column name.

TYPE: str

y

Get the y-axis column name.

TYPE: str

Source code in soundscapy/plotting/iso_plot.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def __init__(
    self,
    data: pd.DataFrame | None = None,
    x: str | np.ndarray | pd.Series | None = "ISOPleasant",
    y: str | np.ndarray | pd.Series | None = "ISOEventful",
    title: str | None = "Soundscape Density Plot",
    hue: str | None = None,
    palette: SeabornPaletteType | None = "colorblind",
    figure: Figure | None = None,  # Removed SubFigure type, don't think we need it
    axes: Axes | np.ndarray | None = None,
) -> None:
    """
    Initialize a ISOPlot instance.

    Parameters
    ----------
    data : pd.DataFrame | None, optional
        The data to be plotted, by default None
    x : str | np.ndarray | pd.Series | None, optional
        Column name or data for x-axis, by default "ISOPleasant"
    y : str | np.ndarray | pd.Series | None, optional
        Column name or data for y-axis, by default "ISOEventful"
    title : str | None, optional
        Title of the plot, by default "Soundscape Density Plot"
    hue : str | None, optional
        Column name for color encoding, by default None
    palette : SeabornPaletteType | None, optional
        Color palette to use, by default "colorblind"
    figure : Figure | SubFigure | None, optional
        Existing figure to plot on, by default None
    axes : Axes | np.ndarray | None, optional
        Existing axes to plot on, by default None

    Examples
    --------
    Create a plot with default parameters:

    >>> import pandas as pd
    >>> import numpy as np
    >>> rng = np.random.default_rng(42)
    >>> data = pd.DataFrame(
    ...    rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
    ...    columns=['ISOPleasant', 'ISOEventful']
    ... )
    >>> plot = ISOPlot()
    >>> isinstance(plot, ISOPlot)
    True

    Create a plot with a DataFrame:

    >>> data = pd.DataFrame(
    ...    np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
    ...          rng.integers(1, 3, 100)],
    ...    columns=['ISOPleasant', 'ISOEventful', 'Group'])
    >>> plot = ISOPlot(data=data, hue='Group')
    >>> plot.hue
    'Group'


    Create a plot directly with arrays:

    >>> x, y = rng.multivariate_normal([0, 0], [[1, 0], [0, 1]], 100).T
    >>> plot = ISOPlot(x=x, y=y)
    >>> isinstance(plot, ISOPlot)
    True

    """
    warnings.warn(
        "`ISOPlot` is currently under development and should be considered "
        "experimental. `ISOPlot` implements an experimental API for creating "
        "layered soundscape circumplex plots. Use with caution.",
        ExperimentalWarning,
        stacklevel=2,
    )

    # Process and validate input data and coordinates
    data, x, y = self._check_data_x_y(data, x, y)
    self._check_data_hue(data, hue)

    # Initialize the main plot context
    self.main_context = PlotContext(
        data=data,
        x=x if isinstance(x, str) else DEFAULT_XCOL,
        y=y if isinstance(y, str) else DEFAULT_YCOL,
        hue=hue,
        title=title,
    )

    # Store additional plot attributes
    self.figure = figure
    self.axes = axes
    self.palette = palette

    # Initialize subplot management
    self.subplot_contexts: list[PlotContext] = []
    self.subplots_params = SubplotsParams()

    # Initialize parameter managers
    self._scatter_params = ScatterParams(
        data=data,
        x=self.main_context.x,
        y=self.main_context.y,
        hue=hue,
        palette=self.palette,
    )

    self._density_params = DensityParams(
        data=data,
        x=self.main_context.x,
        y=self.main_context.y,
        hue=hue,
        palette=self.palette,
    )

    self._simple_density_params = SimpleDensityParams(
        data=data,
        x=self.main_context.x,
        y=self.main_context.y,
        hue=hue,
    )

    self._spi_scatter_params = NotImplementedError
    self._spi_density_params = NotImplementedError
    self._spi_simple_density_params = SPISimpleDensityParams(
        x=self.main_context.x,
        y=self.main_context.y,
    )

    self._style_params = StyleParams()

    # SPI-related attributes
    self._spi_data = None

hue property

hue

Get the hue column name.

title property

title

Get the plot title.

x property

x

Get the x-axis column name.

y property

y

Get the y-axis column name.

add_annotation

add_annotation(text, xy, xytext, arrowprops=None)

Add an annotation to the plot.

PARAMETER DESCRIPTION
text

The text to display in the annotation.

TYPE: str

xy

The point to annotate.

TYPE: tuple[float, float]

xytext

The point at which to place the text.

TYPE: tuple[float, float]

arrowprops

Properties for the arrow connecting the annotation text to the point.

TYPE: dict[str, Any] | None DEFAULT: None

RETURNS DESCRIPTION
ISOPlot

The current plot instance for chaining

Source code in soundscapy/plotting/iso_plot.py
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
def add_annotation(
    self,
    text: str,
    xy: tuple[float, float],
    xytext: tuple[float, float],
    arrowprops: dict[str, Any] | None = None,
) -> ISOPlot:
    """
    Add an annotation to the plot.

    Parameters
    ----------
    text : str
        The text to display in the annotation.
    xy : tuple[float, float]
        The point to annotate.
    xytext : tuple[float, float]
        The point at which to place the text.
    arrowprops : dict[str, Any] | None, optional
        Properties for the arrow connecting the annotation text to the point.

    Returns
    -------
    ISOPlot
        The current plot instance for chaining

    """
    msg = "AnnotationLayer is not yet implemented. "
    raise NotImplementedError(msg)
    # TODO(MitchellAcoustics): Implement AnnotationLayer  # noqa: TD003
    return self.add_layer(
        "AnnotationLayer",
        text=text,
        xy=xy,
        xytext=xytext,
        arrowprops=arrowprops,
    )

add_density

add_density(on_axis=None, data=None, *, include_outline=False, **params)

Add a density layer to specific subplot(s).

PARAMETER DESCRIPTION
on_axis

Target specific axis/axes

TYPE: int | tuple[int, int] | list[int] | None DEFAULT: None

data

Custom data for this specific density plot

TYPE: DataFrame DEFAULT: None

include_outline

Whether to include an outline around the density plot, by default False

TYPE: bool DEFAULT: False

**params

Parameters for the density plot

TYPE: dict DEFAULT: {}

RETURNS DESCRIPTION
ISOPlot

The current plot instance for chaining

Examples:

Add a density layer to all subplots:

>>> import pandas as pd
>>> import numpy as np
>>> rng = np.random.default_rng(42)
>>> data = pd.DataFrame({
...     'ISOPleasant': rng.normal(0.2, 0.25, 50),
...     'ISOEventful': rng.normal(0.15, 0.4, 50),
... })
>>> plot = (
...     ISOPlot(data=data)
...     .create_subplots()
...     .add_density()
...     .style()
... )
>>> plot.show() # xdoctest: +SKIP
>>> len(plot.subplot_contexts[0].layers) == 1
True
>>> plot.close()  # Clean up

Add a density layer with custom settings:

>>> plot = (
...     ISOPlot(data=data)
...     .create_subplots()
...     .add_density(levels=5, alpha=0.7)
...     .style()
... )
>>> plot.show() # xdoctest: +SKIP
>>> len(plot.subplot_contexts[0].layers) == 1
True
>>> plot.close()  # Clean up
Source code in soundscapy/plotting/iso_plot.py
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
def add_density(
    self,
    on_axis: int | tuple[int, int] | list[int] | None = None,
    data: pd.DataFrame | None = None,
    *,
    include_outline: bool = False,
    **params: Any,
) -> ISOPlot:
    """
    Add a density layer to specific subplot(s).

    Parameters
    ----------
    on_axis : int | tuple[int, int] | list[int] | None, optional
        Target specific axis/axes
    data : pd.DataFrame, optional
        Custom data for this specific density plot
    include_outline : bool, optional
        Whether to include an outline around the density plot, by default False
    **params : dict
        Parameters for the density plot

    Returns
    -------
    ISOPlot
        The current plot instance for chaining

    Examples
    --------
    Add a density layer to all subplots:

    >>> import pandas as pd
    >>> import numpy as np
    >>> rng = np.random.default_rng(42)
    >>> data = pd.DataFrame({
    ...     'ISOPleasant': rng.normal(0.2, 0.25, 50),
    ...     'ISOEventful': rng.normal(0.15, 0.4, 50),
    ... })
    >>> plot = (
    ...     ISOPlot(data=data)
    ...     .create_subplots()
    ...     .add_density()
    ...     .style()
    ... )
    >>> plot.show() # xdoctest: +SKIP
    >>> len(plot.subplot_contexts[0].layers) == 1
    True
    >>> plot.close()  # Clean up

    Add a density layer with custom settings:

    >>> plot = (
    ...     ISOPlot(data=data)
    ...     .create_subplots()
    ...     .add_density(levels=5, alpha=0.7)
    ...     .style()
    ... )
    >>> plot.show() # xdoctest: +SKIP
    >>> len(plot.subplot_contexts[0].layers) == 1
    True
    >>> plot.close()  # Clean up

    """
    # Merge default density parameters with provided ones
    density_params = self._density_params.copy()
    density_params.drop("data")
    density_params.update(**params)

    return self.add_layer(
        DensityLayer,
        data=data,
        on_axis=on_axis,
        include_outline=include_outline,
        **density_params.as_dict(drop=["data"]),
    )

add_layer

add_layer(layer_class, data=None, *, on_axis=None, **params)

Add a visualization layer, optionally targeting specific subplot(s).

PARAMETER DESCRIPTION
layer_class

The type of layer to add

TYPE: Layer subclass

on_axis

Target specific axis/axes: - int: Index of subplot (flattened) - tuple: (row, col) coordinates - list: Multiple indices to apply the layer to - None: Apply to all subplots (default)

TYPE: int | tuple[int, int] | list[int] | None DEFAULT: None

data

Custom data for this specific layer, overriding context data

TYPE: DataFrame DEFAULT: None

**params

Parameters for the layer

TYPE: dict DEFAULT: {}

RETURNS DESCRIPTION
ISOPlot

The current plot instance for chaining

Examples:

Add a scatter layer to all subplots:

>>> import pandas as pd
>>> import numpy as np
>>> from soundscapy.plotting.layers import ScatterLayer
>>> rng = np.random.default_rng(42)
>>> data = pd.DataFrame(
...    np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
...          rng.integers(1, 3, 100)],
...    columns=['ISOPleasant', 'ISOEventful', 'Group'])
>>> # Will create 2x2 subplots all with the same data
>>> plot = (ISOPlot(data=data)
...         .create_subplots(nrows=2, ncols=2)
...         .add_layer(ScatterLayer)
...         .style())
>>> plot.show() # xdoctest: +SKIP
>>> all(len(ctx.layers) == 1 for ctx in plot.subplot_contexts)
    True
>>> plot.close()  # Clean up

Add a layer to a specific subplot:

>>> plot = (ISOPlot(data=data)
...         .create_subplots(nrows=2, ncols=2)
...         .add_layer(ScatterLayer, on_axis=0)
...         .style())
>>> plot.show() # xdoctest: +SKIP
>>> len(plot.subplot_contexts[0].layers) == 1
True
>>> all(len(ctx.layers) == 0 for ctx in plot.subplot_contexts[1:])
True
>>> plot.close()

Add a layer to multiple subplots:

>>> plot = (ISOPlot(data=data)
...            .create_subplots(nrows=2, ncols=2)
...            .add_layer(ScatterLayer, on_axis=[0, 2])
...            .style())
>>> plot.show() # xdoctest: +SKIP
>>> len(plot.subplot_contexts[0].layers) == 1
True
>>> len(plot.subplot_contexts[2].layers) == 1
True
>>> len(plot.subplot_contexts[1].layers) == 0
True
>>> plot.close()

Add a layer with custom data to a specific subplot:

>>> custom_data = pd.DataFrame({
...     'ISOPleasant': rng.normal(0.2, 0.1, 50),
...     'ISOEventful': rng.normal(0.15, 0.2, 50),
... })
>>> plot = (ISOPlot(data=data)
...        .create_subplots(nrows=2, ncols=2)
...        .add_layer(ScatterLayer) # Add to all subplots
...        # Add a layer with custom data to the first subplot
...        .add_layer(ScatterLayer, data=data.iloc[:50], on_axis=0, color='red')
...        # Add a layer with custom data to the second subplot
...        .add_layer(ScatterLayer, data=custom_data, on_axis=1)
...        .style())
>>> plot.show() # xdoctest: +SKIP
>>> plot.close()
Source code in soundscapy/plotting/iso_plot.py
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
def add_layer(
    self,
    layer_class: type[Layer],
    data: pd.DataFrame | None = None,
    *,
    on_axis: int | tuple[int, int] | list[int] | None = None,
    **params: Any,
) -> ISOPlot:
    """
    Add a visualization layer, optionally targeting specific subplot(s).

    Parameters
    ----------
    layer_class : Layer subclass
        The type of layer to add
    on_axis : int | tuple[int, int] | list[int] | None, optional
        Target specific axis/axes:
        - int: Index of subplot (flattened)
        - tuple: (row, col) coordinates
        - list: Multiple indices to apply the layer to
        - None: Apply to all subplots (default)
    data : pd.DataFrame, optional
        Custom data for this specific layer, overriding context data
    **params : dict
        Parameters for the layer

    Returns
    -------
    ISOPlot
        The current plot instance for chaining

    Examples
    --------
    Add a scatter layer to all subplots:

    >>> import pandas as pd
    >>> import numpy as np
    >>> from soundscapy.plotting.layers import ScatterLayer
    >>> rng = np.random.default_rng(42)
    >>> data = pd.DataFrame(
    ...    np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
    ...          rng.integers(1, 3, 100)],
    ...    columns=['ISOPleasant', 'ISOEventful', 'Group'])
    >>> # Will create 2x2 subplots all with the same data
    >>> plot = (ISOPlot(data=data)
    ...         .create_subplots(nrows=2, ncols=2)
    ...         .add_layer(ScatterLayer)
    ...         .style())
    >>> plot.show() # xdoctest: +SKIP
    >>> all(len(ctx.layers) == 1 for ctx in plot.subplot_contexts)
        True
    >>> plot.close()  # Clean up

    Add a layer to a specific subplot:

    >>> plot = (ISOPlot(data=data)
    ...         .create_subplots(nrows=2, ncols=2)
    ...         .add_layer(ScatterLayer, on_axis=0)
    ...         .style())
    >>> plot.show() # xdoctest: +SKIP
    >>> len(plot.subplot_contexts[0].layers) == 1
    True
    >>> all(len(ctx.layers) == 0 for ctx in plot.subplot_contexts[1:])
    True
    >>> plot.close()

    Add a layer to multiple subplots:

    >>> plot = (ISOPlot(data=data)
    ...            .create_subplots(nrows=2, ncols=2)
    ...            .add_layer(ScatterLayer, on_axis=[0, 2])
    ...            .style())
    >>> plot.show() # xdoctest: +SKIP
    >>> len(plot.subplot_contexts[0].layers) == 1
    True
    >>> len(plot.subplot_contexts[2].layers) == 1
    True
    >>> len(plot.subplot_contexts[1].layers) == 0
    True
    >>> plot.close()

    Add a layer with custom data to a specific subplot:
    >>> custom_data = pd.DataFrame({
    ...     'ISOPleasant': rng.normal(0.2, 0.1, 50),
    ...     'ISOEventful': rng.normal(0.15, 0.2, 50),
    ... })
    >>> plot = (ISOPlot(data=data)
    ...        .create_subplots(nrows=2, ncols=2)
    ...        .add_layer(ScatterLayer) # Add to all subplots
    ...        # Add a layer with custom data to the first subplot
    ...        .add_layer(ScatterLayer, data=data.iloc[:50], on_axis=0, color='red')
    ...        # Add a layer with custom data to the second subplot
    ...        .add_layer(ScatterLayer, data=custom_data, on_axis=1)
    ...        .style())
    >>> plot.show() # xdoctest: +SKIP
    >>> plot.close()

    """
    # TODO(MitchellAcoustics): Need to handle legend/label creation   # noqa: TD003
    #                          for new data added to a specific subplot
    # Create the layer instance
    layer = layer_class(custom_data=data, **params)

    # Check if we have axes to render on
    self._check_for_axes()

    # If no subplots created yet, add to main context
    if not self.subplot_contexts:
        if self.main_context.ax is None:
            # Get the single axis and assign it to main context
            if isinstance(self.axes, Axes):
                self.main_context.ax = self.axes
            elif isinstance(self.axes, np.ndarray) and self.axes.size > 0:
                self.main_context.ax = self.axes.flatten()[0]

        # Add layer to main context
        self.main_context.layers.append(layer)
        # Render the layer immediately
        layer.render(self.main_context)
        return self

    # Handle various axis targeting options
    target_contexts = self._resolve_target_contexts(on_axis)
    logger.debug(f"N target contexts: {len(target_contexts)}")

    # Add the layer to each target context and render it
    for i, context in enumerate(target_contexts):
        if data is not None and i >= self.subplots_params.n_subplots_by > 0:
            # If custom data is provided, use it for the specific subplot
            break
        context.layers.append(layer)
        layer.render(context)

    return self

add_scatter

add_scatter(data=None, *, on_axis=None, **params)

Add a scatter layer to specific subplot(s).

PARAMETER DESCRIPTION
on_axis

Target specific axis/axes

TYPE: int | tuple[int, int] | list[int] | None DEFAULT: None

data

Custom data for this specific scatter plot

TYPE: DataFrame DEFAULT: None

**params

Parameters for the scatter plot

TYPE: dict DEFAULT: {}

RETURNS DESCRIPTION
ISOPlot

The current plot instance for chaining

Examples:

Add a scatter layer to all subplots:

>>> import pandas as pd
>>> import numpy as np
>>> rng = np.random.default_rng(42)
>>> data = pd.DataFrame(
...    np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
...          rng.integers(1, 3, 100)],
...    columns=['ISOPleasant', 'ISOEventful', 'Group'])
>>> plot = (ISOPlot(data=data)
...           .create_subplots(nrows=2, ncols=1)
...           .add_scatter(s=50, alpha=0.7, hue='Group')
...           .style())
>>> plot.show() # xdoctest: +SKIP
>>> all(len(ctx.layers) == 1 for ctx in plot.subplot_contexts)
True
>>> plot.close()  # Clean up

Add a scatter layer with custom data to a specific subplot:

>>> custom_data = pd.DataFrame({
...     'ISOPleasant': rng.normal(0.2, 0.1, 50),
...     'ISOEventful': rng.normal(0.15, 0.2, 50),
... })
>>> plot = (ISOPlot(data=data)
...            .create_subplots(nrows=2, ncols=1)
...            .add_scatter(hue='Group')
...            .add_scatter(on_axis=0, data=custom_data, color='red')
...            .style())
>>> plot.show() # xdoctest: +SKIP
>>> plot.subplot_contexts[0].layers[1].custom_data is custom_data
True
>>> plot.close()  # Clean up
Source code in soundscapy/plotting/iso_plot.py
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
def add_scatter(
    self,
    data: pd.DataFrame | None = None,
    *,
    on_axis: int | tuple[int, int] | list[int] | None = None,
    **params: Any,
) -> ISOPlot:
    """
    Add a scatter layer to specific subplot(s).

    Parameters
    ----------
    on_axis : int | tuple[int, int] | list[int] | None, optional
        Target specific axis/axes
    data : pd.DataFrame, optional
        Custom data for this specific scatter plot
    **params : dict
        Parameters for the scatter plot

    Returns
    -------
    ISOPlot
        The current plot instance for chaining

    Examples
    --------
    Add a scatter layer to all subplots:

    >>> import pandas as pd
    >>> import numpy as np
    >>> rng = np.random.default_rng(42)
    >>> data = pd.DataFrame(
    ...    np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
    ...          rng.integers(1, 3, 100)],
    ...    columns=['ISOPleasant', 'ISOEventful', 'Group'])
    >>> plot = (ISOPlot(data=data)
    ...           .create_subplots(nrows=2, ncols=1)
    ...           .add_scatter(s=50, alpha=0.7, hue='Group')
    ...           .style())
    >>> plot.show() # xdoctest: +SKIP
    >>> all(len(ctx.layers) == 1 for ctx in plot.subplot_contexts)
    True
    >>> plot.close()  # Clean up

    Add a scatter layer with custom data to a specific subplot:

    >>> custom_data = pd.DataFrame({
    ...     'ISOPleasant': rng.normal(0.2, 0.1, 50),
    ...     'ISOEventful': rng.normal(0.15, 0.2, 50),
    ... })
    >>> plot = (ISOPlot(data=data)
    ...            .create_subplots(nrows=2, ncols=1)
    ...            .add_scatter(hue='Group')
    ...            .add_scatter(on_axis=0, data=custom_data, color='red')
    ...            .style())
    >>> plot.show() # xdoctest: +SKIP
    >>> plot.subplot_contexts[0].layers[1].custom_data is custom_data
    True
    >>> plot.close()  # Clean up

    """
    # Merge default scatter parameters with provided ones
    # Remove data from scatter_params to avoid conflict
    scatter_params = self._scatter_params.copy()
    scatter_params.drop("data")
    scatter_params.update(**params)

    return self.add_layer(
        ScatterLayer,
        data=data,
        on_axis=on_axis,
        **scatter_params.as_dict(drop=["data"]),
    )

add_simple_density

add_simple_density(on_axis=None, data=None, *, include_outline=True, **params)

Add a simple density layer to specific subplot(s).

PARAMETER DESCRIPTION
on_axis

Target specific axis/axes

TYPE: int | tuple[int, int] | list[int] | None DEFAULT: None

data

Custom data for this specific density plot

TYPE: DataFrame DEFAULT: None

thresh

Threshold for density contours, by default 0.5

TYPE: float

levels

Contour levels, by default 2

TYPE: int | Iterable[float]

alpha

Transparency level, by default 0.5

TYPE: float

include_outline

Whether to include an outline around the density plot, by default True

TYPE: bool DEFAULT: True

**params

Additional parameters for the density plot

TYPE: dict DEFAULT: {}

RETURNS DESCRIPTION
ISOPlot

The current plot instance for chaining

Examples:

Add a simple density layer:

>>> import pandas as pd
>>> import numpy as np
>>> rng = np.random.default_rng(42)
>>> data = pd.DataFrame({
...     'ISOPleasant': rng.normal(0.2, 0.25, 30),
...     'ISOEventful': rng.normal(0.15, 0.4, 30),
... })
>>> plot = (
...     ISOPlot(data=data)
...     .create_subplots()
...     .add_scatter()
...     .add_simple_density()
...     .style()
... )
>>> plot.show() # xdoctest: +SKIP
>>> len(plot.subplot_contexts[0].layers) == 2
True
>>> plot.close()  # Clean up

Add a simple density with splitting by group:

>>> data = pd.DataFrame(
...    np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
...          rng.integers(1, 3, 100)],
...    columns=['ISOPleasant', 'ISOEventful', 'Group'])
>>> plot = (
...     ISOPlot(data=data, hue='Group')
...     .create_subplots()
...     .add_scatter()
...     .add_simple_density()
...     .style()
... )
>>> plot.show() # xdoctest: +SKIP
>>> len(plot.subplot_contexts[0].layers) == 2
True
>>> plot.close()
...
Source code in soundscapy/plotting/iso_plot.py
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
def add_simple_density(
    self,
    on_axis: int | tuple[int, int] | list[int] | None = None,
    data: pd.DataFrame | None = None,
    *,
    include_outline: bool = True,
    **params: Any,
) -> ISOPlot:
    """
    Add a simple density layer to specific subplot(s).

    Parameters
    ----------
    on_axis : int | tuple[int, int] | list[int] | None, optional
        Target specific axis/axes
    data : pd.DataFrame, optional
        Custom data for this specific density plot
    thresh : float, optional
        Threshold for density contours, by default 0.5
    levels : int | Iterable[float], optional
        Contour levels, by default 2
    alpha : float, optional
        Transparency level, by default 0.5
    include_outline : bool, optional
        Whether to include an outline around the density plot, by default True
    **params : dict
        Additional parameters for the density plot

    Returns
    -------
    ISOPlot
        The current plot instance for chaining

    Examples
    --------
    Add a simple density layer:

    >>> import pandas as pd
    >>> import numpy as np
    >>> rng = np.random.default_rng(42)
    >>> data = pd.DataFrame({
    ...     'ISOPleasant': rng.normal(0.2, 0.25, 30),
    ...     'ISOEventful': rng.normal(0.15, 0.4, 30),
    ... })
    >>> plot = (
    ...     ISOPlot(data=data)
    ...     .create_subplots()
    ...     .add_scatter()
    ...     .add_simple_density()
    ...     .style()
    ... )
    >>> plot.show() # xdoctest: +SKIP
    >>> len(plot.subplot_contexts[0].layers) == 2
    True
    >>> plot.close()  # Clean up

    Add a simple density with splitting by group:
    >>> data = pd.DataFrame(
    ...    np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
    ...          rng.integers(1, 3, 100)],
    ...    columns=['ISOPleasant', 'ISOEventful', 'Group'])
    >>> plot = (
    ...     ISOPlot(data=data, hue='Group')
    ...     .create_subplots()
    ...     .add_scatter()
    ...     .add_simple_density()
    ...     .style()
    ... )
    >>> plot.show() # xdoctest: +SKIP
    >>> len(plot.subplot_contexts[0].layers) == 2
    True
    >>> plot.close()
    ...

    """
    # Merge default simple density parameters with provided ones
    simple_density_params = self._simple_density_params.copy()
    simple_density_params.drop("data")
    simple_density_params.update(**params)

    return self.add_layer(
        SimpleDensityLayer,
        on_axis=on_axis,
        data=data,
        include_outline=include_outline,
        **simple_density_params.as_dict(drop=["data"]),
    )

add_spi

add_spi(on_axis=None, spi_target_data=None, msn_params=None, *, layer_class=SPISimpleLayer, **params)

Add a SPI layer to specific subplot(s).

PARAMETER DESCRIPTION
on_axis

Target specific axis/axes

TYPE: int | tuple[int, int] | list[int] | None DEFAULT: None

spi_target_data

Custom data for this specific SPI plot

TYPE: DataFrame | ndarray | None DEFAULT: None

msn_params

Parameters for the SPI plot

TYPE: DirectParams | CentredParams | None DEFAULT: None

RETURNS DESCRIPTION
ISOPlot

The current plot instance for chaining

Examples:

Add a SPI layer to all subplots:

>>> import pandas as pd
>>> import numpy as np
>>> from soundscapy.spi import DirectParams
>>> rng = np.random.default_rng(42)
>>>    # Create a DataFrame with random data
>>> data = pd.DataFrame(
...    rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
...    columns=['ISOPleasant', 'ISOEventful']
... )
>>>    # Define MSN parameters for the SPI target
>>> msn_params = DirectParams(
...     xi=np.array([0.5, 0.7]),
...     omega=np.array([[0.1, 0.05], [0.05, 0.1]]),
...     alpha=np.array([0, -5]),
...     )
>>>    # Create the plot with only an SPI layer
>>> plot = (
...     ISOPlot(data=data)
...     .create_subplots()
...     .add_scatter()
...     .add_spi(msn_params=msn_params)
...     .style()
... )
>>> plot.show() # xdoctest: +SKIP
>>> len(plot.subplot_contexts[0].layers) == 2
True
>>> plot.close()  # Clean up

Add an SPI layer over top of 'real' data:

>>> plot = (
...     ISOPlot(data=data)
...     .create_subplots()
...     .add_scatter()
...     .add_density()
...     .add_spi(msn_params=msn_params, show_score="on axis")
...     .style()
... )
>>> plot.show() # xdoctest: +SKIP
>>> len(plot.subplot_contexts[0].layers) == 3
True

Add a SPI layer from spi data:

>>> # Create a custom distribution
>>> from soundscapy.spi import MultiSkewNorm
>>> import soundscapy as sspy
>>> spi_msn = MultiSkewNorm.from_params(msn_params)
>>> # Generate random samples
>>> spi_msn.sample(1000)
>>> data = sspy.add_iso_coords(sspy.isd.load())
>>> data = sspy.isd.select_location_ids(
...     data,
...     ['CamdenTown', 'PancrasLock', 'RussellSq', 'RegentsParkJapan']
... )
>>> mp3 = (
...     ISOPlot(
...         data=data,
...         title="Soundscape Density Plots with corrected ISO coordinates",
...         hue="SessionID",
...     )
...     .create_subplots(
...         subplot_by="LocationID",
...         figsize=(4, 4),
...         auto_allocate_axes=True,
...     )
...     .add_scatter()
...     .add_simple_density(fill=False)
...     .add_spi(spi_target_data=spi_msn.sample_data, show_score="under title")
...     .style()
... )
>>> mp3.show() # xdoctest: +SKIP
>>> plot.close()  # Clean up

BUG: This last doctest doesn't show the spi score under the title

Source code in soundscapy/plotting/iso_plot.py
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
def add_spi(
    self,
    on_axis: int | tuple[int, int] | list[int] | None = None,
    spi_target_data: pd.DataFrame | np.ndarray | None = None,
    msn_params: DirectParams | CentredParams | None = None,
    *,
    layer_class: type[Layer] = SPISimpleLayer,
    **params: Any,
) -> ISOPlot:
    """
    Add a SPI layer to specific subplot(s).

    Parameters
    ----------
    on_axis : int | tuple[int, int] | list[int] | None, optional
        Target specific axis/axes
    spi_target_data : pd.DataFrame | np.ndarray | None, optional
        Custom data for this specific SPI plot
    msn_params : DirectParams | CentredParams | None, optional
        Parameters for the SPI plot

    Returns
    -------
    ISOPlot
        The current plot instance for chaining

    Examples
    --------
    Add a SPI layer to all subplots:

    >>> import pandas as pd
    >>> import numpy as np
    >>> from soundscapy.spi import DirectParams
    >>> rng = np.random.default_rng(42)
    >>>    # Create a DataFrame with random data
    >>> data = pd.DataFrame(
    ...    rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
    ...    columns=['ISOPleasant', 'ISOEventful']
    ... )
    >>>    # Define MSN parameters for the SPI target
    >>> msn_params = DirectParams(
    ...     xi=np.array([0.5, 0.7]),
    ...     omega=np.array([[0.1, 0.05], [0.05, 0.1]]),
    ...     alpha=np.array([0, -5]),
    ...     )
    >>>    # Create the plot with only an SPI layer
    >>> plot = (
    ...     ISOPlot(data=data)
    ...     .create_subplots()
    ...     .add_scatter()
    ...     .add_spi(msn_params=msn_params)
    ...     .style()
    ... )
    >>> plot.show() # xdoctest: +SKIP
    >>> len(plot.subplot_contexts[0].layers) == 2
    True
    >>> plot.close()  # Clean up

    Add an SPI layer over top of 'real' data:
    >>> plot = (
    ...     ISOPlot(data=data)
    ...     .create_subplots()
    ...     .add_scatter()
    ...     .add_density()
    ...     .add_spi(msn_params=msn_params, show_score="on axis")
    ...     .style()
    ... )
    >>> plot.show() # xdoctest: +SKIP
    >>> len(plot.subplot_contexts[0].layers) == 3
    True

    Add a SPI layer from spi data:
    >>> # Create a custom distribution
    >>> from soundscapy.spi import MultiSkewNorm
    >>> import soundscapy as sspy
    >>> spi_msn = MultiSkewNorm.from_params(msn_params)
    >>> # Generate random samples
    >>> spi_msn.sample(1000)
    >>> data = sspy.add_iso_coords(sspy.isd.load())
    >>> data = sspy.isd.select_location_ids(
    ...     data,
    ...     ['CamdenTown', 'PancrasLock', 'RussellSq', 'RegentsParkJapan']
    ... )

    >>> mp3 = (
    ...     ISOPlot(
    ...         data=data,
    ...         title="Soundscape Density Plots with corrected ISO coordinates",
    ...         hue="SessionID",
    ...     )
    ...     .create_subplots(
    ...         subplot_by="LocationID",
    ...         figsize=(4, 4),
    ...         auto_allocate_axes=True,
    ...     )
    ...     .add_scatter()
    ...     .add_simple_density(fill=False)
    ...     .add_spi(spi_target_data=spi_msn.sample_data, show_score="under title")
    ...     .style()
    ... )
    >>> mp3.show() # xdoctest: +SKIP
    >>> plot.close()  # Clean up

    # BUG: This last doctest doesn't show the spi score under the title

    """
    if layer_class == SPISimpleLayer:
        spi_simple_params = self._spi_simple_density_params.copy()
        spi_simple_params.drop("data")
        spi_simple_params.update(**params)

        return self.add_layer(
            layer_class,
            on_axis=on_axis,
            msn_params=msn_params,
            spi_target_data=spi_target_data,
            **spi_simple_params.as_dict(drop=["data"]),
        )
    if layer_class in (SPIDensityLayer, SPIScatterLayer):
        msg = (
            "Only the simple density layer type is currently supported for "
            "SPI plots. Please use SPISimpleLayer"
        )
        raise NotImplementedError(msg)

    msg = "Invalid layer class provided. Expected SPISimpleLayer. "
    raise ValueError(msg)

close

close(fig=None)

Close the figure.

This method is a wrapper around plt.close() to close the figure.

Source code in soundscapy/plotting/iso_plot.py
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
def close(self, fig: int | str | Figure | None = None) -> None:
    """
    Close the figure.

    This method is a wrapper around plt.close() to close the figure.

    """
    if fig is None:
        fig = self.figure
        if fig is None:
            msg = (
                "No figure object provided. "
                "Please create a figure using create_subplots() first."
            )
            raise ValueError(msg)
    plt.close(fig)

create_subplots

create_subplots(nrows=1, ncols=1, figsize=(5, 5), subplot_by=None, subplot_datas=None, subplot_titles=None, *, adjust_figsize=True, auto_allocate_axes=False, **kwargs)

Create subplots for the circumplex plot.

PARAMETER DESCRIPTION
nrows

Number of rows in the subplot grid, by default 1

TYPE: int DEFAULT: 1

ncols

Number of columns in the subplot grid, by default 1

TYPE: int DEFAULT: 1

figsize

Size of the figure (width, height), by default (5, 5)

TYPE: tuple[int, int] DEFAULT: (5, 5)

subplot_by

Column name to create subplots by unique values, by default None

TYPE: str | None DEFAULT: None

subplot_datas

List of dataframes for each subplot, by default None

TYPE: list[DataFrame] | None DEFAULT: None

subplot_titles

List of titles for each subplot, by default None

TYPE: list[str] | None DEFAULT: None

adjust_figsize

Whether to adjust the figure size based on nrows/ncols, by default True

TYPE: bool DEFAULT: True

auto_allocate_axes

Whether to automatically determine nrows/ncols based on data, by default False

TYPE: bool DEFAULT: False

**kwargs

Additional parameters for plt.subplots

DEFAULT: {}

RETURNS DESCRIPTION
ISOPlot

The current plot instance for chaining

Examples:

Create a basic subplot grid:

>>> import pandas as pd
>>> import numpy as np
>>> rng = np.random.default_rng(42)
>>> data = pd.DataFrame(
...    np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
...          rng.integers(1, 3, 100)],
...    columns=['ISOPleasant', 'ISOEventful', 'Group'])
>>> plot = ISOPlot(data=data).create_subplots(nrows=2, ncols=2)
>>> len(plot.subplot_contexts) == 4
True
>>> plot.close()  # Clean up

Create subplots by a column in the data:

>>> plot = (ISOPlot(data=data)
...         .create_subplots(nrows=1, ncols=2, subplot_by='Group'))
>>> len(plot.subplot_contexts) == 2
True
>>> plot.close()  # Clean up

Create subplots with auto-allocation of axes:

>>> plot = (ISOPlot(data=data)
...        .create_subplots(subplot_by='Group', auto_allocate_axes=True))
>>> len(plot.subplot_contexts) == 2
True
>>> plot.close()  # Clean up
Source code in soundscapy/plotting/iso_plot.py
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def create_subplots(
    self,
    nrows: int = 1,
    ncols: int = 1,
    figsize: tuple[int, int] = (5, 5),
    subplot_by: str | None = None,
    subplot_datas: list[pd.DataFrame] | None = None,
    subplot_titles: list[str] | None = None,
    *,
    adjust_figsize: bool = True,
    auto_allocate_axes: bool = False,
    **kwargs,
) -> ISOPlot:
    """
    Create subplots for the circumplex plot.

    Parameters
    ----------
    nrows : int, optional
        Number of rows in the subplot grid, by default 1
    ncols : int, optional
        Number of columns in the subplot grid, by default 1
    figsize : tuple[int, int], optional
        Size of the figure (width, height), by default (5, 5)
    subplot_by : str | None, optional
        Column name to create subplots by unique values, by default None
    subplot_datas : list[pd.DataFrame] | None, optional
        List of dataframes for each subplot, by default None
    subplot_titles : list[str] | None, optional
        List of titles for each subplot, by default None
    adjust_figsize : bool, optional
        Whether to adjust the figure size based on nrows/ncols, by default True
    auto_allocate_axes : bool, optional
        Whether to automatically determine nrows/ncols based on data,
        by default False
    **kwargs :
        Additional parameters for plt.subplots

    Returns
    -------
    ISOPlot
        The current plot instance for chaining

    Examples
    --------
    Create a basic subplot grid:

    >>> import pandas as pd
    >>> import numpy as np
    >>> rng = np.random.default_rng(42)
    >>> data = pd.DataFrame(
    ...    np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
    ...          rng.integers(1, 3, 100)],
    ...    columns=['ISOPleasant', 'ISOEventful', 'Group'])
    >>> plot = ISOPlot(data=data).create_subplots(nrows=2, ncols=2)
    >>> len(plot.subplot_contexts) == 4
    True
    >>> plot.close()  # Clean up

    Create subplots by a column in the data:

    >>> plot = (ISOPlot(data=data)
    ...         .create_subplots(nrows=1, ncols=2, subplot_by='Group'))
    >>> len(plot.subplot_contexts) == 2
    True
    >>> plot.close()  # Clean up

    Create subplots with auto-allocation of axes:

    >>> plot = (ISOPlot(data=data)
    ...        .create_subplots(subplot_by='Group', auto_allocate_axes=True))
    >>> len(plot.subplot_contexts) == 2
    True
    >>> plot.close()  # Clean up

    """
    # Set up subplot params
    self.subplots_params.update(
        nrows=nrows,
        ncols=ncols,
        figsize=figsize,
        subplot_by=subplot_by,
        adjust_figsize=adjust_figsize,
        auto_allocate_axes=auto_allocate_axes,
        **kwargs,
    )
    # Create a list of dataframes and titles for each subplot
    # based on the unique values in the specified column
    if self.subplots_params.subplot_by:
        logger.debug(
            f"Creating subplots by unique values in {self.subplots_params.subplot_by}."
        )
        subplot_datas, subplot_titles, n_subplots_by = self._setup_subplot_by(
            self.subplots_params.subplot_by, subplot_datas, subplot_titles
        )
    else:
        n_subplots_by = -1

    if subplot_titles and self.subplots_params.auto_allocate_axes:
        # Attempt to allocate axes based on the number of subplots
        self.subplots_params.nrows, self.subplots_params.ncols = (
            self._allocate_subplot_axes(subplot_titles)
        )

    if adjust_figsize:
        self.subplots_params.figsize = (
            self.subplots_params.ncols * self.subplots_params.figsize[0],
            self.subplots_params.nrows * self.subplots_params.figsize[1],
        )

    logger.debug(f"Subplot parameters: {self.subplots_params}")

    # Create the figure and axes
    self.figure, self.axes = plt.subplots(
        **self.subplots_params.as_plt_subplots_args()
    )

    # If subplot_datas or subplot_titles are provided, validate them
    if subplot_datas is not None or subplot_titles is not None:
        self._validate_subplots_datas(subplot_datas, subplot_titles)

    # Create PlotContext objects for each subplot
    self.subplot_contexts = []

    for i, ax in enumerate(self.yield_axes_objects()):
        if i >= self._naxes:
            break
        if subplot_by and i >= n_subplots_by:
            logger.debug(f"Created {i + 1} subplots for {subplot_by}.")
            break
        # Get data and title for this subplot if available
        data = (
            subplot_datas[i] if subplot_datas and i < len(subplot_datas) else None
        )
        title = (
            subplot_titles[i]
            if subplot_titles and i < len(subplot_titles)
            else None
        )

        context = self.main_context.create_child(data=data, title=title, ax=ax)
        self.subplot_contexts.append(context)

    return self

get_axes

get_axes()

Get the axes object.

RETURNS DESCRIPTION
Axes | np.ndarray: The axes object to be used for plotting.
RAISES DESCRIPTION
ValueError: If the axes object does not exist.

TypeError: If the axes object is not a valid Axes or ndarray of Axes.

Source code in soundscapy/plotting/iso_plot.py
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
def get_axes(self) -> Axes | np.ndarray:
    """
    Get the axes object.

    Returns
    -------
        Axes | np.ndarray: The axes object to be used for plotting.

    Raises
    ------
        ValueError: If the axes object does not exist.
        TypeError: If the axes object is not a valid Axes or ndarray of Axes.

    """
    self._check_for_axes()
    if isinstance(self.axes, Axes | np.ndarray):
        return self.axes
    msg = "Invalid axes object. Please provide a valid Axes or ndarray of Axes."
    raise TypeError(msg)

get_figure

get_figure()

Get the figure object.

RETURNS DESCRIPTION
Figure | SubFigure: The figure object to be used for plotting.
RAISES DESCRIPTION
ValueError: If the figure object does not exist.

TypeError: If the figure object is not a valid Figure or SubFigure.

Source code in soundscapy/plotting/iso_plot.py
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
def get_figure(self) -> Figure | SubFigure:
    """
    Get the figure object.

    Returns
    -------
        Figure | SubFigure: The figure object to be used for plotting.

    Raises
    ------
        ValueError: If the figure object does not exist.
        TypeError: If the figure object is not a valid Figure or SubFigure.

    """
    if self.figure is None:
        msg = (
            "No figure object provided. "
            "Please create a figure using create_subplots() first."
        )
        raise ValueError(msg)
    if isinstance(self.figure, Figure | SubFigure):
        return self.figure
    msg = "Invalid figure object. Please provide a valid Figure or SubFigure."
    raise TypeError(msg)

get_single_axes

get_single_axes(ax_idx=None)

Get a specific axes object.

PARAMETER DESCRIPTION
ax_idx

The index of the axes to get. If None, returns the first axes. Can be an integer for flattened access or a tuple of (row, col).

TYPE: int | tuple[int, int] | None DEFAULT: None

RETURNS DESCRIPTION
Axes

The requested matplotlib Axes object

RAISES DESCRIPTION
ValueError

If the axes object does not exist or the index is invalid.

TypeError

If the axes object is not a valid Axes or ndarray of Axes.

Source code in soundscapy/plotting/iso_plot.py
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
def get_single_axes(self, ax_idx: int | tuple[int, int] | None = None) -> Axes:
    """
    Get a specific axes object.

    Parameters
    ----------
    ax_idx : int | tuple[int, int] | None, optional
        The index of the axes to get. If None, returns the first axes.
        Can be an integer for flattened access or a tuple of (row, col).

    Returns
    -------
    Axes
        The requested matplotlib Axes object

    Raises
    ------
    ValueError
        If the axes object does not exist or the index is invalid.
    TypeError
        If the axes object is not a valid Axes or ndarray of Axes.

    """
    self._check_for_axes()

    def validate_tuple_axes_index(
        nrows: int, ncols: int, naxes: int, ax_idx: tuple[int, int]
    ) -> None:
        """
        Validate the tuple axes index.

        This checks the ax_idx types and compares the implied number of axes
        with the actual number of axes in the figure.
        """
        if (
            len(ax_idx) != 2  # noqa: PLR2004
            or not isinstance(ax_idx[0], int)
            or not isinstance(ax_idx[1], int)
            or ax_idx[0] < 0
            or ax_idx[1] < 0
        ):
            msg = (
                "Invalid axes index provided. "
                "Expected a tuple of 2 positive integers."
            )
            raise ValueError(msg)

        if ax_idx[0] >= (nrows - 1) or ax_idx[1] >= (ncols - 1):
            msg = (
                "Invalid axes index provided."
                f" The figure contains {nrows} rows and {ncols} columns. "
                f"ax_idx implied {ax_idx[0] + 1} rows and {ax_idx[1] + 1} columns."
            )
            raise ValueError(msg)

        idx_implied_n_axes = (ax_idx[0] + 1) * (ax_idx[1] + 1)
        if naxes < idx_implied_n_axes:
            msg = (
                "Invalid axes index provided."
                f" The figure contains {naxes} axes. "
                f"ax_idx implied {idx_implied_n_axes} axes."
            )
            raise ValueError(msg)

    def validate_int_axes_index(naxes: int, ax_idx: int) -> None:
        """
        Validate the integer axes index.

        This checks the ax_idx type and compares the implied number of axes
        with the actual number of axes in the figure.
        """
        if not isinstance(ax_idx, int) or ax_idx < 0:
            msg = "Invalid axes index provided. Expected a positive integer."
            raise ValueError(msg)

        if (ax_idx + 1) > naxes:
            msg = (
                "Invalid axes index provided."
                f" The figure contains {naxes} axes. "
                f"ax_idx implied {ax_idx + 1} axes."
            )
            raise ValueError(msg)

    if isinstance(self.axes, np.ndarray) and ax_idx is not None:
        if isinstance(ax_idx, tuple):
            validate_tuple_axes_index(self._nrows, self._ncols, self._naxes, ax_idx)
            return self.axes[ax_idx[0], ax_idx[1]]

        validate_int_axes_index(self._naxes, ax_idx)
        return self.axes.flatten()[ax_idx]

    if isinstance(self.axes, Axes) and (ax_idx == 0 or ax_idx is None):
        return self.axes

    msg = "Invalid axes index provided."
    raise ValueError(msg)

savefig

savefig(*args, **kwargs)

Save the figure.

This method is a wrapper around plt.savefig() to save the figure.

Source code in soundscapy/plotting/iso_plot.py
580
581
582
583
584
585
586
587
588
589
590
591
592
593
def savefig(self, *args: Any, **kwargs: Any) -> None:
    """
    Save the figure.

    This method is a wrapper around plt.savefig() to save the figure.

    """
    if self.figure is None:
        msg = (
            "No figure object provided. "
            "Please create a figure using create_subplots() first."
        )
        raise ValueError(msg)
    self.figure.savefig(*args, **kwargs)

show

show()

Show the figure.

This method is a wrapper around plt.show() to display the figure.

Source code in soundscapy/plotting/iso_plot.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
def show(self) -> None:
    """
    Show the figure.

    This method is a wrapper around plt.show() to display the figure.

    """
    if self.figure is None:
        msg = (
            "No figure object provided. "
            "Please create a figure using create_subplots() first."
        )
        raise ValueError(msg)
    if self._has_subplots:
        plt.tight_layout()
    plt.show()

style

style(**kwargs)

Apply styling to the plot.

PARAMETER DESCRIPTION
**kwargs

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
ISOPlot

The current plot instance for chaining

Examples:

Apply styling with default parameters:

>>> import pandas as pd
>>> import numpy as np
>>> rng = np.random.default_rng(42)
>>> # Create simple data for styling example
>>> data = pd.DataFrame(
...     np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
...             rng.integers(1, 3, 100)],
...     columns=['ISOPleasant', 'ISOEventful', 'Group'])
>>> # Create plot with default styling
>>> plot = (
...    ISOPlot(data=data)
...       .create_subplots()
...       .add_scatter()
...       .style()
... )
>>> plot.show() # xdoctest: +SKIP
>>> plot.get_figure() is not None
True
>>> plot.close()  # Clean up

Apply styling with custom parameters:

>>> plot = (
...         ISOPlot(data=data)
...         .create_subplots()
...         .add_scatter()
...         .style(xlim=(-2, 2), ylim=(-2, 2), primary_lines=False)
... )
>>> plot.show() # xdoctest: +SKIP
>>> plot.get_figure() is not None
True
>>> plot.close()  # Clean up

Demonstrate the fluent interface (method chaining):

>>> # Create plot with method chaining
>>> plot = (
...     ISOPlot(data=data)
...     .create_subplots(nrows=1, ncols=1)
...     .add_scatter(alpha=0.7)
...     .add_density(levels=5)
...     .style(title_fontsize=14)
... )
>>> plot.show() # xdoctest: +SKIP
>>> # Verify results
>>> isinstance(plot, ISOPlot)
True
>>> plot.close()  # Clean up
Source code in soundscapy/plotting/iso_plot.py
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
def style(
    self,
    **kwargs: Any,
) -> ISOPlot:
    """
    Apply styling to the plot.

    Parameters
    ----------
    **kwargs: Styling parameters to override defaults

    Returns
    -------
    ISOPlot
        The current plot instance for chaining

    Examples
    --------
    Apply styling with default parameters:

    >>> import pandas as pd
    >>> import numpy as np
    >>> rng = np.random.default_rng(42)
    >>> # Create simple data for styling example
    >>> data = pd.DataFrame(
    ...     np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
    ...             rng.integers(1, 3, 100)],
    ...     columns=['ISOPleasant', 'ISOEventful', 'Group'])
    >>> # Create plot with default styling
    >>> plot = (
    ...    ISOPlot(data=data)
    ...       .create_subplots()
    ...       .add_scatter()
    ...       .style()
    ... )
    >>> plot.show() # xdoctest: +SKIP
    >>> plot.get_figure() is not None
    True
    >>> plot.close()  # Clean up

    Apply styling with custom parameters:

    >>> plot = (
    ...         ISOPlot(data=data)
    ...         .create_subplots()
    ...         .add_scatter()
    ...         .style(xlim=(-2, 2), ylim=(-2, 2), primary_lines=False)
    ... )
    >>> plot.show() # xdoctest: +SKIP
    >>> plot.get_figure() is not None
    True
    >>> plot.close()  # Clean up

    Demonstrate the fluent interface (method chaining):

    >>> # Create plot with method chaining
    >>> plot = (
    ...     ISOPlot(data=data)
    ...     .create_subplots(nrows=1, ncols=1)
    ...     .add_scatter(alpha=0.7)
    ...     .add_density(levels=5)
    ...     .style(title_fontsize=14)
    ... )
    >>> plot.show() # xdoctest: +SKIP
    >>> # Verify results
    >>> isinstance(plot, ISOPlot)
    True
    >>> plot.close()  # Clean up

    """
    self._style_params.update(**kwargs)
    self._check_for_axes()

    self._set_style()
    self._circumplex_grid()
    self._set_title()
    self._set_axes_titles()
    self._primary_labels()
    if self._style_params.get("primary_lines"):
        self._primary_lines()
    if self._style_params.get("diagonal_lines"):
        self._diagonal_lines_and_labels()

    if self._style_params.get("legend_loc") is not False:
        self._move_legend()

    return self

yield_axes_objects

yield_axes_objects()

Generate a sequence of axes objects to iterate over.

This method is a helper to iterate over all axes in the figure, whether the figure contains a single Axes object or an array of Axes objects.

YIELDS DESCRIPTION
Axes

Individual matplotlib Axes objects from the current figure.

Source code in soundscapy/plotting/iso_plot.py
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
def yield_axes_objects(self) -> Generator[Axes, None, None]:
    """
    Generate a sequence of axes objects to iterate over.

    This method is a helper to iterate over all axes in the figure,
    whether the figure contains a single Axes object or an array of Axes objects.

    Yields
    ------
    Axes
        Individual matplotlib Axes objects from the current figure.

    """
    if isinstance(self.axes, np.ndarray):
        yield from self.axes.flatten()
    elif isinstance(self.axes, Axes):
        yield self.axes

show_submodules: true