Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ENH] Group shading #199

Merged
merged 9 commits into from
Apr 15, 2021
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ Plots for plotting power spectra with shaded regions.

plot_spectrum_shading
plot_spectra_shading
plot_spectra_yshade

Plot Model Properties & Parameters
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expand Down
68 changes: 68 additions & 0 deletions fooof/plts/spectra.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from itertools import repeat, cycle

import numpy as np
from scipy.stats import sem

from fooof.core.modutils import safe_import, check_dependency
from fooof.plts.settings import PLT_FIGSIZES
Expand Down Expand Up @@ -172,3 +173,70 @@ def plot_spectra_shading(freqs, power_spectra, shades, shade_colors='r',

style_spectrum_plot(ax, plot_kwargs.get('log_freqs', False),
plot_kwargs.get('log_powers', False))


@savefig
@style_plot
@check_dependency(plt, 'matplotlib')
def plot_spectra_yshade(freqs, power_spectra, shade='std', average='mean', scale=1,
log_freqs=False, log_powers=False, color=None, label=None,
ax=None, **plot_kwargs):
"""Plot standard deviation or error as a shaded region around the mean spectrum.

Parameters
----------
freqs : 1d array
Frequency values, to be plotted on the x-axis.
power_spectra : 1d or 2d array
Power values, to be plotted on the y-axis. ``shade`` must be provided if 1d.
shade : 'std', 'sem', 1d array or callable, optional, default: 'std'
Approach for shading above/below the mean spectrum.
average : 'mean', 'median' or callable, optional, default: 'mean'
Averaging approach for the average spectrum to plot. Only used if power_spectra is 2d.
scale : int, optional, default: 1
Factor to multiply the plotted shade by.
log_freqs : bool, optional, default: False
Whether to plot the frequency axis in log spacing.
log_powers : bool, optional, default: False
Whether to plot the power axis in log spacing.
color : str, optional, default: None
Line color of the spectrum.
label : str, optional, default: None
Legend label for the spectrum.
ax : matplotlib.Axes, optional
Figure axes upon which to plot.
**plot_kwargs
Keyword arguments to be passed to `plot_spectra` or to the plot call.
"""

if isinstance(shade, str) and power_spectra.ndim != 2:
TomDonoghue marked this conversation as resolved.
Show resolved Hide resolved
raise ValueError('Power spectra must be 2d if shade is not given.')

ax = check_ax(ax, plot_kwargs.pop('figsize', PLT_FIGSIZES['spectral']))

# Set plot data & labels, logging if requested
plt_freqs = np.log10(freqs) if log_freqs else freqs
plt_powers = np.log10(power_spectra) if log_powers else power_spectra

# Organize mean spectrum to plot
avg_funcs = {'mean' : np.mean, 'median' : np.median}
avg_func = avg_funcs[average] if isinstance(average, str) else average
avg_powers = avg_func(plt_powers, axis=0) if plt_powers.ndim == 2 else plt_powers
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will require an average callable to have an axis arg. A custom callable may not have this, but np functions will. We may just want to require an array of length equal to the first dimension of plt_powers to be returned?

If a numpy callable is expected, we should make a note.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeh, great points. I think what you've done makes a ton of sense to address this.


# Plot average power spectrum
ax.plot(plt_freqs, avg_powers, linewidth=2.0, color=color, label=label)

# Organize shading to plot
shade_funcs = {'std' : np.std, 'sem' : sem}
shade_func = shade_funcs[shade] if isinstance(shade, str) else shade
shade_vals = scale * shade_func(plt_powers, axis=0) \
if isinstance(shade, str) else scale * shade
TomDonoghue marked this conversation as resolved.
Show resolved Hide resolved
upper_shade = avg_powers + shade_vals
lower_shade = avg_powers - shade_vals

# Plot +/- yshading around spectrum
alpha = plot_kwargs.pop('alpha', 0.25)
ax.fill_between(plt_freqs, lower_shade, upper_shade,
alpha=alpha, color=color, **plot_kwargs)

style_spectrum_plot(ax, log_freqs, log_powers)
28 changes: 28 additions & 0 deletions fooof/tests/plts/test_spectra.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Tests for fooof.plts.spectra."""

from pytest import raises

import numpy as np

from fooof.tests.tutils import plot_test
Expand Down Expand Up @@ -59,3 +61,29 @@ def test_plot_spectra_shading(tfg, skip_if_no_mpl):
shades=[8, 12], add_center=True, log_freqs=True, log_powers=True,
labels=['A', 'B'], save_fig=True, file_path=TEST_PLOTS_PATH,
file_name='test_plot_spectra_shading_kwargs.png')

@plot_test
def test_plot_spectra_yshade(skip_if_no_mpl, tfg):

freqs = tfg.freqs
powers = tfg.power_spectra

# Invalid 1d array, without shade
with raises(ValueError):
plot_spectra_yshade(freqs, powers[0])

# Plot with 2d array
plot_spectra_yshade(freqs, powers, shade='std',
save_fig=True, file_path=TEST_PLOTS_PATH,
file_name='test_plot_spectra_yshade1.png')

# Plot shade with given 1d array
plot_spectra_yshade(freqs, np.mean(powers, axis=0),
shade=np.std(powers, axis=0),
save_fig=True, file_path=TEST_PLOTS_PATH,
file_name='test_plot_spectra_yshade2.png')

# Plot shade with different average and shade approaches
plot_spectra_yshade(freqs, powers, shade='sem', average='median',
save_fig=True, file_path=TEST_PLOTS_PATH,
file_name='test_plot_spectra_yshade3.png')