soundscapy¶
soundscapy
¶
Soundscapy is a Python library for soundscape analysis and visualisation.
| MODULE | DESCRIPTION |
|---|---|
audio |
Provides tools for working with audio signals, particularly binaural recordings. |
data |
Soundscape data module. |
databases |
Soundscapy Databases Module. |
db |
Soundscapy Databases Module. |
isd |
Module for handling the International Soundscape Database (ISD). |
iso_plot |
Main module for creating circumplex plots using different backends. |
likert |
Plotting functions for visualizing Likert scale data. |
plotting |
Soundscapy Plotting Module. |
processing |
Soundscape survey data processing module. |
r_wrapper |
Module for wrapping R functionality with rpy2. |
satp |
Soundscape Attributes Translation (SATP) calculation module. |
spi |
Soundscape Perception Indices (SPI) calculation module. |
sspylogging |
Logging configuration for Soundscapy. |
surveys |
Soundscapy Surveys Package. |
| CLASS | DESCRIPTION |
|---|---|
ISOPlot |
A class for creating circumplex plots using different backends. |
| FUNCTION | DESCRIPTION |
|---|---|
create_iso_subplots |
Create a set of subplots displaying data visualizations for soundscape analysis. |
density |
Plot a density plot of ISOCoordinates. |
jointplot |
Create a jointplot with a central distribution and marginal plots. |
scatter |
Plot ISOcoordinates as scatter points on a soundscape circumplex grid. |
paq_likert |
Create a Likert scale plot for PAQ (Perceived Affective Quality) data. |
paq_radar_plot |
Generate a radar/spider plot of PAQ values. |
stacked_likert |
Create a stacked Likert scale plot for a single column of survey data. |
disable_logging |
Disable all Soundscapy logging. |
enable_debug |
Quickly enable DEBUG level logging to console. |
get_logger |
Get the Soundscapy logger instance. |
setup_logging |
Set up logging for Soundscapy with sensible defaults. |
add_iso_coords |
Calculate and add ISO coordinates as new columns in the DataFrame. |
ipsatize |
Participant-level ipsatization for circumplex analysis. |
rename_paqs |
Rename the PAQ columns in a DataFrame to standard PAQ IDs. |
ISOPlot
¶
ISOPlot(
data: DataFrame | None = None,
x: str | ndarray | Series | None = "ISOPleasant",
y: str | ndarray | Series | None = "ISOEventful",
title: str | None = "Soundscape Density Plot",
hue: str | None = None,
palette: SeabornPaletteType | None = "colorblind",
figure: Figure | None = None,
axes: Axes | ndarray | None = 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()
Initialize a ISOPlot instance.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
The data to be plotted, by default None
TYPE:
|
x
|
Column name or data for x-axis, by default "ISOPleasant"
TYPE:
|
y
|
Column name or data for y-axis, by default "ISOEventful"
TYPE:
|
title
|
Title of the plot, by default "Soundscape Density Plot"
TYPE:
|
hue
|
Column name for color encoding, by default None
TYPE:
|
palette
|
Color palette to use, by default "colorblind"
TYPE:
|
figure
|
Existing figure to plot on, by default None
TYPE:
|
axes
|
Existing axes to plot on, by default None
TYPE:
|
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 |
|---|---|
create_subplots |
Create subplots for the circumplex plot. |
show |
Show the figure. |
close |
Close the figure. |
savefig |
Save the figure. |
get_figure |
Get the figure object. |
get_axes |
Get the axes object. |
get_single_axes |
Get a specific axes object. |
yield_axes_objects |
Generate a sequence of axes objects to iterate over. |
add_layer |
Add a visualization layer, optionally targeting specific subplot(s). |
add_scatter |
Add a scatter layer to specific subplot(s). |
add_spi |
Add a SPI layer to specific subplot(s). |
add_density |
Add a density layer to specific subplot(s). |
add_simple_density |
Add a simple density layer to specific subplot(s). |
add_annotation |
Add an annotation to the plot. |
style |
Apply styling to the plot. |
| ATTRIBUTE | DESCRIPTION |
|---|---|
x |
Get the x-axis column name.
TYPE:
|
y |
Get the y-axis column name.
TYPE:
|
hue |
Get the hue column name.
TYPE:
|
title |
Get the plot title.
TYPE:
|
Source code in src/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 | |
create_subplots
¶
create_subplots(
nrows: int = 1,
ncols: int = 1,
figsize: tuple[int, int] = (5, 5),
subplot_by: str | None = None,
subplot_datas: list[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.
| PARAMETER | DESCRIPTION |
|---|---|
nrows
|
Number of rows in the subplot grid, by default 1
TYPE:
|
ncols
|
Number of columns in the subplot grid, by default 1
TYPE:
|
figsize
|
Size of the figure (width, height), by default (5, 5) |
subplot_by
|
Column name to create subplots by unique values, by default None
TYPE:
|
subplot_datas
|
List of dataframes for each subplot, by default None
TYPE:
|
subplot_titles
|
List of titles for each subplot, by default None |
adjust_figsize
|
Whether to adjust the figure size based on nrows/ncols, by default True
TYPE:
|
auto_allocate_axes
|
Whether to automatically determine nrows/ncols based on data, by default False
TYPE:
|
**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 src/soundscapy/plotting/iso_plot.py
400 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 | |
show
¶
Show the figure.
This method is a wrapper around plt.show() to display the figure.
Source code in src/soundscapy/plotting/iso_plot.py
close
¶
Close the figure.
This method is a wrapper around plt.close() to close the figure.
Source code in src/soundscapy/plotting/iso_plot.py
savefig
¶
Save the figure.
This method is a wrapper around plt.savefig() to save the figure.
Source code in src/soundscapy/plotting/iso_plot.py
get_figure
¶
Get the figure object.
| RETURNS | DESCRIPTION |
|---|---|
Figure | SubFigure
|
The matplotlib Figure or SubFigure object associated with this plot. |
| 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 src/soundscapy/plotting/iso_plot.py
get_axes
¶
Get the axes object.
| RETURNS | DESCRIPTION |
|---|---|
Axes | ndarray
|
The matplotlib Axes object or array of Axes associated with this plot. |
| 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 src/soundscapy/plotting/iso_plot.py
get_single_axes
¶
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). |
| 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 src/soundscapy/plotting/iso_plot.py
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 870 871 872 873 874 875 876 877 | |
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 src/soundscapy/plotting/iso_plot.py
add_layer
¶
add_layer(
layer_class: type[Layer],
data: 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).
| PARAMETER | DESCRIPTION |
|---|---|
layer_class
|
The type of layer to add |
on_axis
|
Target specific axis/axes:
TYPE:
|
data
|
Custom data for this specific layer, overriding context data
TYPE:
|
**params
|
Parameters for the layer
TYPE:
|
| 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()
>>> 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()
>>> 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()
>>> 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()
>>> plot.close()
Source code in src/soundscapy/plotting/iso_plot.py
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 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 | |
add_scatter
¶
add_scatter(
data: DataFrame | None = None,
*,
on_axis: int
| tuple[int, int]
| list[int]
| None = None,
**params: Any,
) -> ISOPlot
Add a scatter layer to specific subplot(s).
| PARAMETER | DESCRIPTION |
|---|---|
on_axis
|
Target specific axis/axes
TYPE:
|
data
|
Custom data for this specific scatter plot
TYPE:
|
**params
|
Parameters for the scatter plot
TYPE:
|
| 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()
>>> 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()
>>> plot.subplot_contexts[0].layers[1].custom_data is custom_data
True
>>> plot.close() # Clean up
Source code in src/soundscapy/plotting/iso_plot.py
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 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 | |
add_spi
¶
add_spi(
on_axis: int
| tuple[int, int]
| list[int]
| None = None,
spi_target_data: DataFrame | 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).
| PARAMETER | DESCRIPTION |
|---|---|
on_axis
|
Target specific axis/axes
TYPE:
|
spi_target_data
|
Custom data for this specific SPI plot
TYPE:
|
msn_params
|
Parameters for the SPI plot
TYPE:
|
| 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()
>>> 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()
>>> 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()
>>> plot.close() # Clean up
Source code in src/soundscapy/plotting/iso_plot.py
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 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 | |
add_density
¶
add_density(
on_axis: int
| tuple[int, int]
| list[int]
| None = None,
data: DataFrame | None = None,
*,
include_outline: bool = False,
**params: Any,
) -> ISOPlot
Add a density layer to specific subplot(s).
| PARAMETER | DESCRIPTION |
|---|---|
on_axis
|
Target specific axis/axes
TYPE:
|
data
|
Custom data for this specific density plot
TYPE:
|
include_outline
|
Whether to include an outline around the density plot, by default False
TYPE:
|
**params
|
Parameters for the density plot
TYPE:
|
| 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()
>>> 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()
>>> len(plot.subplot_contexts[0].layers) == 1
True
>>> plot.close() # Clean up
Source code in src/soundscapy/plotting/iso_plot.py
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 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 | |
add_simple_density
¶
add_simple_density(
on_axis: int
| tuple[int, int]
| list[int]
| None = None,
data: DataFrame | None = None,
*,
include_outline: bool = True,
**params: Any,
) -> ISOPlot
Add a simple density layer to specific subplot(s).
| PARAMETER | DESCRIPTION |
|---|---|
on_axis
|
Target specific axis/axes
TYPE:
|
data
|
Custom data for this specific density plot
TYPE:
|
include_outline
|
Whether to include an outline around the density plot, by default True
TYPE:
|
**params
|
Additional parameters for the density plot. Useful options include
TYPE:
|
| 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()
>>> 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()
>>> len(plot.subplot_contexts[0].layers) == 2
True
>>> plot.close()
...
Source code in src/soundscapy/plotting/iso_plot.py
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 1479 1480 1481 1482 1483 1484 1485 | |
add_annotation
¶
add_annotation(
text: str,
xy: tuple[float, float],
xytext: tuple[float, float],
arrowprops: dict[str, Any] | None = None,
) -> ISOPlot
Add an annotation to the plot.
| PARAMETER | DESCRIPTION |
|---|---|
text
|
The text to display in the annotation.
TYPE:
|
xy
|
The point to annotate. |
xytext
|
The point at which to place the text. |
arrowprops
|
Properties for the arrow connecting the annotation text to the point. |
| RETURNS | DESCRIPTION |
|---|---|
ISOPlot
|
The current plot instance for chaining |
Source code in src/soundscapy/plotting/iso_plot.py
style
¶
Apply styling to the plot.
| PARAMETER | DESCRIPTION |
|---|---|
**kwargs
|
TYPE:
|
| 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()
>>> 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()
>>> 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()
>>> # Verify results
>>> isinstance(plot, ISOPlot)
True
>>> plot.close() # Clean up
Source code in src/soundscapy/plotting/iso_plot.py
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 1605 1606 1607 1608 1609 1610 1611 | |
create_iso_subplots
¶
create_iso_subplots(
data: DataFrame | list[DataFrame],
x: str = "ISOPleasant",
y: str = "ISOEventful",
subplot_by: str | None = None,
title: str | None = "Soundscapy Plot",
plot_layers: Literal[
"scatter", "density", "simple_density"
]
| Sequence[
Literal["scatter", "simple_density", "density"]
] = ("scatter", "density"),
*,
subplot_size: tuple[int, int] = (4, 4),
subplot_titles: Literal["by_group", "numbered"]
| list[str]
| None = "by_group",
subplot_title_prefix: str = "Plot",
nrows: int | None = None,
ncols: int | None = None,
**kwargs,
) -> tuple[Figure, np.ndarray]
Create a set of subplots displaying data visualizations for soundscape analysis.
This function generates a collection of subplots, where each subplot corresponds to a subset of the input data. The subplots can display scatter plots, density plots, or simplified density plots, and can be organized by specific grouping criteria. Users can specify titles, overall size, row and column layout, and layering of plot types.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Input data to be visualized. Can be a single data frame or a list of data frames for use in multiple subplots.
TYPE:
|
x
|
The name of the column in the data to be used for the x-axis. Default is "ISOPleasant".
TYPE:
|
y
|
The name of the column in the data to be used for the y-axis. Default is "ISOEventful".
TYPE:
|
subplot_by
|
The column name by which to group data into subplots. If None, data is not grouped and plotted in a single set of axes. Default is None.
TYPE:
|
title
|
The overarching title of the figure. If None, no overall title is added. Default is "Soundscapy Plot".
TYPE:
|
plot_layers
|
Type(s) of plot layers to include in each subplot. Can be a single type or a sequence of types. Default is ("scatter", "density").
TYPE:
|
subplot_size
|
Size of each subplot in inches as (width, height). Default is (4, 4). |
subplot_titles
|
Determines how subplot titles are assigned. Options are "by_group" (titles derived from group names), "numbered" (titles as indices), or a list of custom titles. If None, no titles are added. Default is "by_group".
TYPE:
|
subplot_title_prefix
|
Prefix for subplot titles if "numbered" is selected as
TYPE:
|
nrows
|
Number of rows for the subplot grid. If None, automatically calculated based on the number of subplots. Default is None.
TYPE:
|
ncols
|
Number of columns for the subplot grid. If None, automatically calculated based on the number of subplots. Default is None.
TYPE:
|
**kwargs
|
Additional keyword arguments to pass to matplotlib's
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Figure, ndarray]
|
A tuple containing:
|
Examples:
Basic subplots with default settings:
>>> import soundscapy as sspy
>>> import matplotlib.pyplot as plt
>>> import pandas as pd
>>> data = sspy.isd.load()
>>> data = sspy.add_iso_coords(data)
>>> four_locs = sspy.isd.select_location_ids(data,
... ['CamdenTown', 'PancrasLock', 'RegentsParkJapan', 'RegentsParkFields']
... )
>>> fig, axes = sspy.create_iso_subplots(four_locs, subplot_by="LocationID")
>>> plt.show()
Create subplots by specifying a list of data
>>> data1 = pd.DataFrame({'ISOPleasant': np.random.uniform(-1, 1, 50),
... 'ISOEventful': np.random.uniform(-1, 1, 50)})
>>> data2 = pd.DataFrame({'ISOPleasant': np.random.uniform(-1, 1, 50),
... 'ISOEventful': np.random.uniform(-1, 1, 50)})
>>> fig, axes = create_iso_subplots(
... [data1, data2], plot_layers="scatter", nrows=1, ncols=2
... )
>>> plt.show()
>>> assert len(axes) == 2
>>> plt.close('all')
Source code in src/soundscapy/plotting/plot_functions.py
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 | |
density
¶
density(
data: DataFrame,
title: str | None = "Soundscape Density Plot",
ax: Axes | None = None,
*,
x: str | None = "ISOPleasant",
y: str | None = "ISOEventful",
hue: str | None = None,
incl_scatter: bool = True,
density_type: str = "full",
palette: SeabornPaletteType | None = "colorblind",
scatter_kws: dict | None = None,
legend: Literal[
"auto", "brief", "full", False
] = "auto",
prim_labels: bool | None = None,
**kwargs,
) -> Axes
Plot a density plot of ISOCoordinates.
Creates a kernel density estimate visualization of data distribution on a circumplex grid with the custom Soundscapy styling for soundscape circumplex visualisations. Can optionally include a scatter plot of the underlying data points.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Input data structure containing coordinate data, typically with ISOPleasant and ISOEventful columns.
TYPE:
|
title
|
Title to add to circumplex plot, by default "Soundscape Density Plot"
TYPE:
|
ax
|
Pre-existing axes object to use for the plot, by default None
If
TYPE:
|
x
|
Column name for x variable, by default "ISOPleasant"
TYPE:
|
y
|
Column name for y variable, by default "ISOEventful"
TYPE:
|
hue
|
Grouping variable that will produce density contours with different colors. Can be either categorical or numeric, although color mapping will behave differently in latter case, by default None
TYPE:
|
incl_scatter
|
Whether to include a scatter plot of the data points, by default True
TYPE:
|
density_type
|
Type of density plot to draw. "full" uses default parameters, "simple" uses a lower number of levels (2), higher threshold (0.5), and lower alpha (0.5) for a cleaner visualization, by default "full"
TYPE:
|
palette
|
Method for choosing the colors to use when mapping the hue semantic. String values are passed to seaborn.color_palette(). List or dict values imply categorical mapping, while a colormap object implies numeric mapping, by default "colorblind"
TYPE:
|
scatter_kws
|
Keyword arguments to pass to
TYPE:
|
legend
|
How to draw the legend. If "brief", numeric hue variables will be represented with a sample of evenly spaced values. If "full", every group will get an entry in the legend. If "auto", choose between brief or full representation based on number of levels. If False, no legend data is added and no legend is drawn, by default "auto"
TYPE:
|
prim_labels
|
Deprecated. Use xlabel and ylabel parameters instead.
TYPE:
|
**kwargs
|
Additional styling parameters. Common options include
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Axes
|
Axes object containing the plot. |
Notes
This function will raise a warning if the dataset has fewer than RECOMMENDED_MIN_SAMPLES (30) data points, as density plots are not reliable with small sample sizes.
Examples:
Basic density plot with default settings:
>>> import soundscapy as sspy
>>> import matplotlib.pyplot as plt
>>> data = sspy.isd.load()
>>> data = sspy.add_iso_coords(data)
>>> ax = sspy.density(data)
>>> plt.show()
Simple density plot with fewer contour levels:
Density plot with custom styling:
>>> sub_data = sspy.isd.select_location_ids(
... data, ['CamdenTown', 'PancrasLock', 'RegentsParkJapan', 'RegentsParkFields'])
>>> ax = sspy.density(
... sub_data,
... hue="SessionID",
... incl_scatter=True,
... legend_loc="upper right",
... fill = False,
... density_type = "simple",
... )
>>> plt.show()
Add density to existing plots:
>>> fig, axes = plt.subplots(1, 2, figsize=(12, 6))
>>> axes[0] = sspy.density(
... sspy.isd.select_location_ids(data, ['CamdenTown', 'PancrasLock']),
... ax=axes[0], title="CamdenTown and PancrasLock", hue="LocationID",
... density_type="simple"
... )
>>> axes[1] = sspy.density(
... sspy.isd.select_location_ids(data, ['RegentsParkJapan']),
... ax=axes[1], title="RegentsParkJapan"
... )
>>> plt.tight_layout()
>>> plt.show()
>>> plt.close('all')
Source code in src/soundscapy/plotting/plot_functions.py
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 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 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 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 | |
jointplot
¶
jointplot(
data: DataFrame,
*,
x: str = DEFAULT_XCOL,
y: str = DEFAULT_YCOL,
title: str | None = "Soundscape Joint Plot",
hue: str | None = None,
incl_scatter: bool = True,
density_type: str = "full",
palette: SeabornPaletteType | None = "colorblind",
color: ColorType | None = DEFAULT_COLOR,
scatter_kws: dict[str, Any] | None = None,
incl_outline: bool = False,
alpha: float = DEFAULT_SEABORN_PARAMS["alpha"],
fill: bool = True,
levels: int | tuple[float, ...] = 10,
thresh: float = 0.05,
bw_adjust: float = DEFAULT_BW_ADJUST,
legend: Literal[
"auto", "brief", "full", False
] = "auto",
prim_labels: bool | None = None,
joint_kws: dict[str, Any] | None = None,
marginal_kws: dict[str, Any] | None = None,
marginal_kind: str = "kde",
**kwargs,
) -> sns.JointGrid
Create a jointplot with a central distribution and marginal plots.
Creates a visualization with a main plot (density or scatter) in the center and marginal distribution plots along the x and y axes. The main plot uses the custom Soundscapy styling for soundscape circumplex visualisations, and the marginals show the individual distributions of each variable.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Input data structure containing coordinate data, typically with ISOPleasant and ISOEventful columns.
TYPE:
|
x
|
Column name for x variable, by default "ISOPleasant"
TYPE:
|
y
|
Column name for y variable, by default "ISOEventful"
TYPE:
|
title
|
Title to add to the jointplot, by default "Soundscape Joint Plot"
TYPE:
|
hue
|
Grouping variable that will produce plots with different colors. Can be either categorical or numeric, although color mapping will behave differently in latter case, by default None
TYPE:
|
incl_scatter
|
Whether to include a scatter plot of the data points in the joint plot, by default True
TYPE:
|
density_type
|
Type of density plot to draw. "full" uses default parameters, "simple" uses a lower number of levels (2), higher threshold (0.5), and lower alpha (0.5) for a cleaner visualization, by default "full"
TYPE:
|
palette
|
Method for choosing the colors to use when mapping the hue semantic. String values are passed to seaborn.color_palette(). List or dict values imply categorical mapping, while a colormap object implies numeric mapping, by default "colorblind"
TYPE:
|
scatter_kws
|
Additional keyword arguments to pass to scatter plot if incl_scatter is True, by default None |
incl_outline
|
Whether to include an outline for the density contours, by default False
TYPE:
|
alpha
|
Opacity level for the density fill, by default 0.8
TYPE:
|
fill
|
Whether to fill the density contours, by default True
TYPE:
|
levels
|
Number of contour levels or specific levels to draw. A vector argument must have increasing values in [0, 1], by default 10 |
thresh
|
Lowest iso-proportion level at which to draw contours, by default 0.05
TYPE:
|
bw_adjust
|
Factor that multiplicatively scales the bandwidth. Increasing will make the density estimate smoother, by default 1.2
TYPE:
|
legend
|
How to draw the legend for hue mapping, by default "auto"
TYPE:
|
prim_labels
|
Deprecated. Use xlabel and ylabel parameters instead.
TYPE:
|
joint_kws
|
Additional keyword arguments to pass to the joint plot, by default None |
marginal_kws
|
Additional keyword arguments to pass to the marginal plots, by default {"fill": True, "common_norm": False} |
marginal_kind
|
Type of plot to draw in the marginal axes, either "kde" for kernel density estimation or "hist" for histogram, by default "kde"
TYPE:
|
**kwargs
|
Additional styling parameters. Common options include
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
JointGrid
|
The seaborn JointGrid object containing the plot |
Notes
This function will raise a warning if the dataset has fewer than RECOMMENDED_MIN_SAMPLES (30) data points, as density plots are not reliable with small sample sizes.
Examples:
Basic jointplot with default settings:
>>> import soundscapy as sspy
>>> import matplotlib.pyplot as plt
>>> data = sspy.isd.load()
>>> data = sspy.add_iso_coords(data)
>>> g = sspy.jointplot(data)
>>> plt.show()
Jointplot with histogram marginals:
Jointplot with custom styling and grouping:
>>> g = sspy.jointplot(
... data,
... hue="LocationID",
... incl_scatter=True,
... density_type="simple",
... diagonal_lines=True,
... figsize=(6, 6),
... title="Grouped Soundscape Analysis"
... )
>>> plt.show()
>>> plt.close('all')
Source code in src/soundscapy/plotting/plot_functions.py
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 1187 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 1315 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 1391 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 | |
scatter
¶
scatter(
data: DataFrame,
title: str | None = "Soundscape Scatter Plot",
ax: Axes | None = None,
*,
x: str | None = "ISOPleasant",
y: str | None = "ISOEventful",
hue: str | None = None,
palette: SeabornPaletteType | None = "colorblind",
legend: Literal[
"auto", "brief", "full", False
] = "auto",
prim_labels: bool | None = None,
**kwargs,
) -> Axes
Plot ISOcoordinates as scatter points on a soundscape circumplex grid.
Creates a scatter plot of data on a standardized circumplex grid with the custom Soundscapy styling for soundscape circumplex visualisations.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Input data structure containing coordinate data, typically with ISOPleasant and ISOEventful columns.
TYPE:
|
x
|
Column name for x variable, by default "ISOPleasant"
TYPE:
|
y
|
Column name for y variable, by default "ISOEventful"
TYPE:
|
title
|
Title to add to circumplex plot, by default "Soundscape Scatter Plot"
TYPE:
|
ax
|
Pre-existing matplotlib axes for the plot, by default None
If
TYPE:
|
hue
|
Grouping variable that will produce points with different colors. Can be either categorical or numeric, although color mapping will behave differently in latter case, by default None
TYPE:
|
palette
|
Method for choosing the colors to use when mapping the hue semantic. String values are passed to seaborn.color_palette(). List or dict values imply categorical mapping, while a colormap object implies numeric mapping, by default "colorblind"
TYPE:
|
legend
|
How to draw the legend. If "brief", numeric hue and size variables will be represented with a sample of evenly spaced values. If "full", every group will get an entry in the legend. If "auto", choose between brief or full representation based on number of levels. If False, no legend data is added and no legend is drawn, by default "auto"
TYPE:
|
prim_labels
|
Deprecated. Use xlabel and ylabel parameters instead.
TYPE:
|
**kwargs
|
Additional style arguments. Common options include
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Axes
|
Axes object containing the plot. |
Notes
This function applies special styling appropriate for circumplex plots including gridlines, axis labels, and proportional axes.
Examples:
Basic scatter plot with default settings:
>>> import soundscapy as sspy
>>> import matplotlib.pyplot as plt
>>> data = sspy.isd.load()
>>> data = sspy.add_iso_coords(data)
>>> ax = sspy.scatter(data)
>>> plt.show()
Scatter plot with grouping by location:
>>> ax = sspy.scatter(data, hue="LocationID", diagonal_lines=True, legend=False)
>>> plt.show()
>>> plt.close('all')
Source code in src/soundscapy/plotting/plot_functions.py
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 | |
paq_likert
¶
paq_likert(
data: DataFrame,
title: str = "Stacked Likert Plot",
paq_cols: list[str] = PAQ_IDS,
*,
legend: bool = True,
ax: Axes | None = None,
plot_percentage: bool = False,
bar_labels: bool = True,
**kwargs,
) -> None
Create a Likert scale plot for PAQ (Perceived Affective Quality) data.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
DataFrame containing PAQ values.
TYPE:
|
paq_cols
|
List of column names containing PAQ data, by default PAQ_IDS. |
title
|
Plot title, by default "Stacked Likert Plot".
TYPE:
|
legend
|
Whether to show the legend, by default True.
TYPE:
|
ax
|
Matplotlib axes to plot on, by default None.
TYPE:
|
plot_percentage
|
Whether to show percentages instead of absolute values, by default False.
TYPE:
|
bar_labels
|
Whether to show bar labels, by default True.
TYPE:
|
**kwargs
|
Additional keyword arguments passed to plot_likert.plot_likert.
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
None
|
This function does not return anything, it plots directly to the given axes. |
Examples:
>>> import soundscapy as sspy
>>> data = sspy.isd.load(['CamdenTown'])
>>> paq_likert(data, "Camden Town Likert data")
>>> plt.show()
Source code in src/soundscapy/plotting/likert.py
paq_radar_plot
¶
paq_radar_plot(
data: DataFrame,
ax: Axes | None = None,
index: str | None = None,
angles: list[float] | tuple[float, ...] = EQUAL_ANGLES,
*,
figsize: tuple[float, float] = (8, 8),
palette: str | Sequence[str] | None = "colorblind",
alpha: float = 0.25,
linewidth: float = 1.5,
linestyle: str = "solid",
ylim: tuple[int, int] = (1, 5),
title: str | None = None,
label_pad: float | None = 15,
legend_loc: str = "upper right",
legend_bbox_to_anchor: tuple[float, float] | None = (
0.1,
0.1,
),
) -> Axes
Generate a radar/spider plot of PAQ values.
This function creates a radar plot showing PAQ (Perceived Affective Quality) values from a dataframe. The radar plot displays values for all 8 PAQ dimensions arranged in a circular layout.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
DataFrame containing PAQ values. Must contain columns matching PAQ_LABELS or they will be filtered out.
TYPE:
|
ax
|
Existing polar subplot axes to plot to. If None, new axes will be created.
TYPE:
|
index
|
Column(s) to set as index for the data. Useful for labeling in the legend.
TYPE:
|
figsize
|
Figure size (width, height) in inches, by default (8, 8). Only used when creating new axes. |
palette
|
Colors for the plot lines and fills. Can be:
If None, a default colormap will be used. |
alpha
|
Transparency for the filled areas, by default 0.25
TYPE:
|
linewidth
|
Width of the plot lines, by default 1.5
TYPE:
|
linestyle
|
Style of the plot lines, by default "solid"
TYPE:
|
ylim
|
Y-axis limits (min, max), by default (1, 5) for standard Likert scale |
title
|
Plot title, by default None
TYPE:
|
label_pad
|
Padding for category labels, by default 15
TYPE:
|
legend_loc
|
Legend location, by default "upper right"
TYPE:
|
legend_bbox_to_anchor
|
Legend bbox_to_anchor parameter, by default (0.1, 0.1) |
| RETURNS | DESCRIPTION |
|---|---|
Axes
|
Matplotlib Axes with radar plot |
Examples:
>>> import pandas as pd
>>> import matplotlib.pyplot as plt
>>> from soundscapy.plotting.likert import paq_radar_plot
>>>
>>> # Sample data with PAQ values for two locations
>>> data = pd.DataFrame({
... "Location": ["Park", "Street"],
... "pleasant": [4.2, 2.1],
... "vibrant": [3.5, 4.2],
... "eventful": [2.8, 4.5],
... "chaotic": [1.5, 3.9],
... "annoying": [1.2, 3.7],
... "monotonous": [2.5, 1.8],
... "uneventful": [3.1, 1.9],
... "calm": [4.3, 1.4]
... })
>>>
>>> # Create radar plot with the "Location" column as index
>>> ax = paq_radar_plot(data, index="Location", title="PAQ Comparison")
>>> plt.show()
Source code in src/soundscapy/plotting/likert.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 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 | |
stacked_likert
¶
stacked_likert(
data: DataFrame,
column: str = "appropriate",
title: str = "Stacked Likert Plot",
*,
legend: bool = True,
ax: Axes | None = None,
plot_percentage: bool = False,
bar_labels: bool = True,
**kwargs,
) -> None
Create a stacked Likert scale plot for a single column of survey data.
This function creates a horizontal stacked bar chart showing the distribution of responses across Likert scale categories for a specified column. The data is automatically cleaned by removing NaN values and converted to categorical format for plotting.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
DataFrame containing survey response data.
TYPE:
|
column
|
Name of the column to plot, by default "appropriate".
TYPE:
|
title
|
Plot title, by default "Stacked Likert Plot".
TYPE:
|
legend
|
Whether to show the legend, by default True.
TYPE:
|
ax
|
Matplotlib axes to plot on. If None, new axes will be created, by default None.
TYPE:
|
plot_percentage
|
Whether to show percentages instead of absolute values, by default False.
TYPE:
|
bar_labels
|
Whether to show bar labels, by default True.
TYPE:
|
**kwargs
|
Additional keyword arguments passed to plot_likert.plot_likert.
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
None
|
This function does not return anything, it plots directly to the given axes. |
Warnings
This is an experimental function that applies brute force data cleaning. Use with caution as it may change in future versions.
Examples:
>>> import pandas as pd
>>> import matplotlib.pyplot as plt
>>> from soundscapy.plotting.likert import stacked_likert
>>>
>>> # Sample survey data
>>> data = pd.DataFrame({
... "appropriate": [1, 2, 3, 4, 5, 3, 4, 2, 5, 1]
... })
>>>
>>> # Create stacked Likert plot
>>> stacked_likert(data, column="appropriate", title="Appropriateness Ratings")
>>> plt.show()
Source code in src/soundscapy/plotting/likert.py
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 | |
disable_logging
¶
Disable all Soundscapy logging.
Examples:
>>> from soundscapy import disable_logging
>>> disable_logging()
>>> # No more logging messages will be shown
Source code in src/soundscapy/sspylogging.py
enable_debug
¶
Quickly enable DEBUG level logging to console.
This is a convenience function for debugging during interactive sessions.
Examples:
>>> from soundscapy import enable_debug
>>> enable_debug()
>>> # Now all debug messages will be shown
Source code in src/soundscapy/sspylogging.py
get_logger
¶
Get the Soundscapy logger instance.
Returns the loguru logger configured for Soundscapy. This is mainly for advanced users who want to configure logging themselves.
| RETURNS | DESCRIPTION |
|---|---|
Logger
|
The loguru logger instance |
Examples:
>>> from soundscapy import get_logger
>>> logger = get_logger()
>>> logger.debug("Custom debug message")
Source code in src/soundscapy/sspylogging.py
setup_logging
¶
setup_logging(
level: str = "INFO",
log_file: str | Path | None = None,
format_level: str = "basic",
) -> None
Set up logging for Soundscapy with sensible defaults.
| PARAMETER | DESCRIPTION |
|---|---|
level
|
Logging level for console output. Options: "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"
TYPE:
|
log_file
|
Path to a log file. If provided, all messages (including DEBUG) will be logged to this file. |
format_level
|
Format complexity level. Options:
TYPE:
|
Examples:
>>> from soundscapy import setup_logging
>>> # Basic usage - show INFO level and above in console
>>> setup_logging()
>>>
>>> # Enable DEBUG level and log to file
>>> setup_logging(level="DEBUG", log_file="soundscapy.log")
>>>
>>> # Use detailed format for debugging
>>> setup_logging(level="DEBUG", format_level="detailed")
Source code in src/soundscapy/sspylogging.py
add_iso_coords
¶
add_iso_coords(
data: DataFrame,
val_range: tuple[int, int] = (1, 5),
names: tuple[str, str] = ("ISOPleasant", "ISOEventful"),
angles: tuple[int, ...] = EQUAL_ANGLES,
*,
overwrite: bool = False,
) -> pd.DataFrame
Calculate and add ISO coordinates as new columns in the DataFrame.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Input DataFrame containing PAQ data
TYPE:
|
val_range
|
(min, max) range of original PAQ responses, by default (1, 5) |
names
|
Names for new coordinate columns, by default ("ISOPleasant", "ISOEventful")
TYPE:
|
angles
|
Angles for each PAQ in degrees, by default EQUAL_ANGLES |
overwrite
|
Whether to overwrite existing ISO coordinate columns, by default False
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
DataFrame with new ISO coordinate columns added |
| RAISES | DESCRIPTION |
|---|---|
Warning
|
If ISO coordinate columns already exist and overwrite is False |
Examples:
>>> import pandas as pd
>>> df = pd.DataFrame({
... 'PAQ1': [4, 2], 'PAQ2': [3, 5], 'PAQ3': [2, 4], 'PAQ4': [1, 3],
... 'PAQ5': [5, 1], 'PAQ6': [3, 2], 'PAQ7': [4, 3], 'PAQ8': [2, 5]
... })
>>> df_with_iso = add_iso_coords(df)
>>> df_with_iso[['ISOPleasant', 'ISOEventful']].round(2)
ISOPleasant ISOEventful
0 -0.03 -0.28
1 0.47 0.18
Source code in src/soundscapy/surveys/processing.py
ipsatize
¶
ipsatize(
data: DataFrame,
method: Literal[
"grand_mean", "column_wise", "row_wise"
] = "grand_mean",
participant_col: str = "participant",
scales: list[str] | None = None,
) -> pd.DataFrame
Participant-level ipsatization for circumplex analysis.
Removes systematic response biases before computing a correlation matrix. The choice of method depends on the study design and the type of bias being corrected.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
DataFrame containing PAQ scale columns and (for participant-level methods) a grouping column.
TYPE:
|
method
|
Centering strategy:
TYPE:
|
participant_col
|
Column used to group observations by participant. Required for
TYPE:
|
scales
|
PAQ column names to centre. Defaults to :data: |
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
DataFrame containing only the scale columns with centred values.
The |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If |
Examples:
>>> import pandas as pd
>>> data = pd.DataFrame({
... 'PAQ1': [50., 60., 40., 30.], 'PAQ2': [50., 60., 40., 30.],
... 'PAQ3': [50., 60., 40., 30.], 'PAQ4': [50., 60., 40., 30.],
... 'PAQ5': [50., 60., 40., 30.], 'PAQ6': [50., 60., 40., 30.],
... 'PAQ7': [50., 60., 40., 30.], 'PAQ8': [50., 60., 40., 30.],
... 'participant': ['A', 'A', 'B', 'B'],
... })
>>> result = ipsatize(data, method="grand_mean")
>>> result['PAQ1'].tolist()
[-5.0, 5.0, 5.0, -5.0]
Source code in src/soundscapy/surveys/processing.py
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 | |
rename_paqs
¶
Rename the PAQ columns in a DataFrame to standard PAQ IDs.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input DataFrame containing PAQ data.
TYPE:
|
paq_aliases
|
Specify which PAQs are to be renamed. If None, will check if the column names are in pre-defined options. If a tuple, the order must match PAQ_IDS. If a dict, keys are current names and values are desired PAQ IDs. |
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
DataFrame with renamed PAQ columns. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If paq_aliases is not a tuple, list, or dictionary. |
Examples:
>>> import pandas as pd
>>> df = pd.DataFrame({
... 'pleasant': [4, 3],
... 'vibrant': [2, 5],
... 'other_col': [1, 2]
... })
>>> rename_paqs(df)
PAQ1 PAQ2 other_col
0 4 2 1
1 3 5 2
>>> df_custom = pd.DataFrame({
... 'pl': [4, 3],
... 'vb': [2, 5],
... })
>>> rename_paqs(df_custom, paq_aliases={'pl': 'PAQ1', 'vb': 'PAQ2'})
PAQ1 PAQ2
0 4 2
1 3 5