Compute and visualize ERDS maps#

This example calculates and displays ERDS maps of event-related EEG data. ERDS (sometimes also written as ERD/ERS) is short for event-related desynchronization (ERD) and event-related synchronization (ERS) [1]. Conceptually, ERD corresponds to a decrease in power in a specific frequency band relative to a baseline. Similarly, ERS corresponds to an increase in power. An ERDS map is a time/frequency representation of ERD/ERS over a range of frequencies [2]. ERDS maps are also known as ERSP (event-related spectral perturbation) [3].

In this example, we use an EEG BCI data set containing two different motor imagery tasks (imagined hand and feet movement). Our goal is to generate ERDS maps for each of the two tasks.

First, we load the data and create epochs of 5s length. The data set contains multiple channels, but we will only consider C3, Cz, and C4. We compute maps containing frequencies ranging from 2 to 35Hz. We map ERD to red color and ERS to blue color, which is customary in many ERDS publications. Finally, we perform cluster-based permutation tests to estimate significant ERDS values (corrected for multiple comparisons within channels).

# Authors: Clemens Brunner <clemens.brunner@gmail.com>
#          Felix Klotzsche <klotzsche@cbs.mpg.de>
#
# License: BSD-3-Clause

As usual, we import everything we need.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import TwoSlopeNorm
import pandas as pd
import seaborn as sns
import mne
from mne.datasets import eegbci
from mne.io import concatenate_raws, read_raw_edf
from mne.time_frequency import tfr_multitaper
from mne.stats import permutation_cluster_1samp_test as pcluster_test

First, we load and preprocess the data. We use runs 6, 10, and 14 from subject 1 (these runs contains hand and feet motor imagery).

fnames = eegbci.load_data(subject=1, runs=(6, 10, 14))
raw = concatenate_raws([read_raw_edf(f, preload=True) for f in fnames])

raw.rename_channels(lambda x: x.strip('.'))  # remove dots from channel names

events, _ = mne.events_from_annotations(raw, event_id=dict(T1=2, T2=3))
Exception ignored in: <_io.FileIO name='/home/circleci/project/mne/data/eegbci_checksums.txt' mode='rb' closefd=True>
Traceback (most recent call last):
  File "<decorator-gen-566>", line 12, in load_data
ResourceWarning: unclosed file <_io.BufferedReader name='/home/circleci/project/mne/data/eegbci_checksums.txt'>
Extracting EDF parameters from /home/circleci/mne_data/MNE-eegbci-data/files/eegmmidb/1.0.0/S001/S001R06.edf...
EDF file detected
Setting channel info structure...
Creating raw.info structure...
Reading 0 ... 19999  =      0.000 ...   124.994 secs...
Extracting EDF parameters from /home/circleci/mne_data/MNE-eegbci-data/files/eegmmidb/1.0.0/S001/S001R10.edf...
EDF file detected
Setting channel info structure...
Creating raw.info structure...
Reading 0 ... 19999  =      0.000 ...   124.994 secs...
Extracting EDF parameters from /home/circleci/mne_data/MNE-eegbci-data/files/eegmmidb/1.0.0/S001/S001R14.edf...
EDF file detected
Setting channel info structure...
Creating raw.info structure...
Reading 0 ... 19999  =      0.000 ...   124.994 secs...
Used Annotations descriptions: ['T1', 'T2']

Now we can create 5-second epochs around events of interest.

tmin, tmax = -1, 4
event_ids = dict(hands=2, feet=3)  # map event IDs to tasks

epochs = mne.Epochs(raw, events, event_ids, tmin - 0.5, tmax + 0.5,
                    picks=('C3', 'Cz', 'C4'), baseline=None, preload=True)
Not setting metadata
45 matching events found
No baseline correction applied
0 projection items activated
Using data from preloaded Raw for 45 events and 961 original time points ...
0 bad epochs dropped

Here we set suitable values for computing ERDS maps. Note especially the cnorm variable, which sets up an asymmetric colormap where the middle color is mapped to zero, even though zero is not the middle value of the colormap range. This does two things: it ensures that zero values will be plotted in white (given that below we select the RdBu colormap), and it makes synchronization and desynchronization look equally prominent in the plots, even though their extreme values are of different magnitudes.

freqs = np.arange(2, 36)  # frequencies from 2-35Hz
vmin, vmax = -1, 1.5  # set min and max ERDS values in plot
baseline = (-1, 0)  # baseline interval (in s)
cnorm = TwoSlopeNorm(vmin=vmin, vcenter=0, vmax=vmax)  # min, center & max ERDS

kwargs = dict(n_permutations=100, step_down_p=0.05, seed=1,
              buffer_size=None, out_type='mask')  # for cluster test

Finally, we perform time/frequency decomposition over all epochs.

tfr = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs, use_fft=True,
                     return_itc=False, average=False, decim=2)
tfr.crop(tmin, tmax).apply_baseline(baseline, mode="percent")

for event in event_ids:
    # select desired epochs for visualization
    tfr_ev = tfr[event]
    fig, axes = plt.subplots(1, 4, figsize=(12, 4),
                             gridspec_kw={"width_ratios": [10, 10, 10, 1]})
    for ch, ax in enumerate(axes[:-1]):  # for each channel
        # positive clusters
        _, c1, p1, _ = pcluster_test(tfr_ev.data[:, ch], tail=1, **kwargs)
        # negative clusters
        _, c2, p2, _ = pcluster_test(tfr_ev.data[:, ch], tail=-1, **kwargs)

        # note that we keep clusters with p <= 0.05 from the combined clusters
        # of two independent tests; in this example, we do not correct for
        # these two comparisons
        c = np.stack(c1 + c2, axis=2)  # combined clusters
        p = np.concatenate((p1, p2))  # combined p-values
        mask = c[..., p <= 0.05].any(axis=-1)

        # plot TFR (ERDS map with masking)
        tfr_ev.average().plot([ch], cmap="RdBu", cnorm=cnorm, axes=ax,
                              colorbar=False, show=False, mask=mask,
                              mask_style="mask")

        ax.set_title(epochs.ch_names[ch], fontsize=10)
        ax.axvline(0, linewidth=1, color="black", linestyle=":")  # event
        if ch != 0:
            ax.set_ylabel("")
            ax.set_yticklabels("")
    fig.colorbar(axes[0].images[-1], cax=axes[-1]).ax.set_yscale("linear")
    fig.suptitle(f"ERDS ({event})")
    plt.show()
  • ERDS (hands), C3, Cz, C4
  • ERDS (feet), C3, Cz, C4
[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
[Parallel(n_jobs=1)]: Done   1 out of   1 | elapsed:    0.2s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   2 out of   2 | elapsed:    0.4s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   3 out of   3 | elapsed:    0.5s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   3 out of   3 | elapsed:    0.5s finished
Not setting metadata
Applying baseline correction (mode: percent)
Using a threshold of 1.724718
stat_fun(H1): min=-8.552076 max=3.183231
Running initial clustering …
Found 80 clusters

  0%|          | Permuting : 0/99 [00:00<?,       ?it/s]
  9%|9         | Permuting : 9/99 [00:00<00:00,  261.00it/s]
 21%|##1       | Permuting : 21/99 [00:00<00:00,  308.75it/s]
 34%|###4      | Permuting : 34/99 [00:00<00:00,  335.07it/s]
 47%|####7     | Permuting : 47/99 [00:00<00:00,  348.30it/s]
 61%|######    | Permuting : 60/99 [00:00<00:00,  356.45it/s]
 74%|#######3  | Permuting : 73/99 [00:00<00:00,  361.71it/s]
 87%|########6 | Permuting : 86/99 [00:00<00:00,  365.56it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  370.22it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  366.25it/s]
Step-down-in-jumps iteration #1 found 0 clusters to exclude from subsequent iterations
Using a threshold of -1.724718
stat_fun(H1): min=-8.552076 max=3.183231
Running initial clustering …
Found 67 clusters

  0%|          | Permuting : 0/99 [00:00<?,       ?it/s]
 12%|#2        | Permuting : 12/99 [00:00<00:00,  353.88it/s]
 25%|##5       | Permuting : 25/99 [00:00<00:00,  369.68it/s]
 37%|###7      | Permuting : 37/99 [00:00<00:00,  364.56it/s]
 51%|#####     | Permuting : 50/99 [00:00<00:00,  369.87it/s]
 63%|######2   | Permuting : 62/99 [00:00<00:00,  366.03it/s]
 75%|#######4  | Permuting : 74/99 [00:00<00:00,  364.02it/s]
 87%|########6 | Permuting : 86/99 [00:00<00:00,  362.62it/s]
 99%|#########8| Permuting : 98/99 [00:00<00:00,  361.61it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  363.25it/s]
Step-down-in-jumps iteration #1 found 1 cluster to exclude from subsequent iterations

  0%|          | Permuting : 0/99 [00:00<?,       ?it/s]
 12%|#2        | Permuting : 12/99 [00:00<00:00,  353.46it/s]
 25%|##5       | Permuting : 25/99 [00:00<00:00,  369.16it/s]
 37%|###7      | Permuting : 37/99 [00:00<00:00,  364.46it/s]
 51%|#####     | Permuting : 50/99 [00:00<00:00,  369.92it/s]
 63%|######2   | Permuting : 62/99 [00:00<00:00,  366.75it/s]
 75%|#######4  | Permuting : 74/99 [00:00<00:00,  364.30it/s]
 88%|########7 | Permuting : 87/99 [00:00<00:00,  367.77it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  367.33it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  366.71it/s]
Step-down-in-jumps iteration #2 found 0 additional clusters to exclude from subsequent iterations
No baseline correction applied
Using a threshold of 1.724718
stat_fun(H1): min=-4.528367 max=3.706422
Running initial clustering …
Found 88 clusters

  0%|          | Permuting : 0/99 [00:00<?,       ?it/s]
 11%|#1        | Permuting : 11/99 [00:00<00:00,  324.57it/s]
 23%|##3       | Permuting : 23/99 [00:00<00:00,  340.51it/s]
 35%|###5      | Permuting : 35/99 [00:00<00:00,  345.79it/s]
 48%|####8     | Permuting : 48/99 [00:00<00:00,  356.34it/s]
 63%|######2   | Permuting : 62/99 [00:00<00:00,  369.16it/s]
 76%|#######5  | Permuting : 75/99 [00:00<00:00,  372.21it/s]
 89%|########8 | Permuting : 88/99 [00:00<00:00,  374.32it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  378.32it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  375.27it/s]
Step-down-in-jumps iteration #1 found 1 cluster to exclude from subsequent iterations

  0%|          | Permuting : 0/99 [00:00<?,       ?it/s]
 12%|#2        | Permuting : 12/99 [00:00<00:00,  354.22it/s]
 24%|##4       | Permuting : 24/99 [00:00<00:00,  354.87it/s]
 37%|###7      | Permuting : 37/99 [00:00<00:00,  365.58it/s]
 51%|#####     | Permuting : 50/99 [00:00<00:00,  370.99it/s]
 64%|######3   | Permuting : 63/99 [00:00<00:00,  374.15it/s]
 77%|#######6  | Permuting : 76/99 [00:00<00:00,  376.05it/s]
 90%|########9 | Permuting : 89/99 [00:00<00:00,  377.59it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  381.14it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  379.06it/s]
Step-down-in-jumps iteration #2 found 0 additional clusters to exclude from subsequent iterations
Using a threshold of -1.724718
stat_fun(H1): min=-4.528367 max=3.706422
Running initial clustering …
Found 58 clusters

  0%|          | Permuting : 0/99 [00:00<?,       ?it/s]
 12%|#2        | Permuting : 12/99 [00:00<00:00,  353.62it/s]
 25%|##5       | Permuting : 25/99 [00:00<00:00,  369.86it/s]
 37%|###7      | Permuting : 37/99 [00:00<00:00,  364.95it/s]
 51%|#####     | Permuting : 50/99 [00:00<00:00,  370.20it/s]
 62%|######1   | Permuting : 61/99 [00:00<00:00,  360.25it/s]
 75%|#######4  | Permuting : 74/99 [00:00<00:00,  364.88it/s]
 87%|########6 | Permuting : 86/99 [00:00<00:00,  363.24it/s]
 99%|#########8| Permuting : 98/99 [00:00<00:00,  361.97it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  364.20it/s]
Step-down-in-jumps iteration #1 found 0 clusters to exclude from subsequent iterations
No baseline correction applied
Using a threshold of 1.724718
stat_fun(H1): min=-6.581589 max=3.346448
Running initial clustering …
Found 67 clusters

  0%|          | Permuting : 0/99 [00:00<?,       ?it/s]
 11%|#1        | Permuting : 11/99 [00:00<00:00,  324.02it/s]
 24%|##4       | Permuting : 24/99 [00:00<00:00,  354.96it/s]
 37%|###7      | Permuting : 37/99 [00:00<00:00,  365.27it/s]
 49%|####9     | Permuting : 49/99 [00:00<00:00,  362.43it/s]
 64%|######3   | Permuting : 63/99 [00:00<00:00,  373.64it/s]
 77%|#######6  | Permuting : 76/99 [00:00<00:00,  375.64it/s]
 90%|########9 | Permuting : 89/99 [00:00<00:00,  377.04it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  374.74it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  373.30it/s]
Step-down-in-jumps iteration #1 found 0 clusters to exclude from subsequent iterations
Using a threshold of -1.724718
stat_fun(H1): min=-6.581589 max=3.346448
Running initial clustering …
Found 69 clusters

  0%|          | Permuting : 0/99 [00:00<?,       ?it/s]
 12%|#2        | Permuting : 12/99 [00:00<00:00,  353.44it/s]
 24%|##4       | Permuting : 24/99 [00:00<00:00,  354.27it/s]
 36%|###6      | Permuting : 36/99 [00:00<00:00,  354.47it/s]
 49%|####9     | Permuting : 49/99 [00:00<00:00,  362.25it/s]
 62%|######1   | Permuting : 61/99 [00:00<00:00,  360.60it/s]
 74%|#######3  | Permuting : 73/99 [00:00<00:00,  359.68it/s]
 87%|########6 | Permuting : 86/99 [00:00<00:00,  363.94it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  367.77it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  366.09it/s]
Step-down-in-jumps iteration #1 found 0 clusters to exclude from subsequent iterations
No baseline correction applied
Using a threshold of 1.713872
stat_fun(H1): min=-3.754759 max=3.360704
Running initial clustering …
Found 71 clusters

  0%|          | Permuting : 0/99 [00:00<?,       ?it/s]
 12%|#2        | Permuting : 12/99 [00:00<00:00,  353.97it/s]
 23%|##3       | Permuting : 23/99 [00:00<00:00,  339.33it/s]
 35%|###5      | Permuting : 35/99 [00:00<00:00,  345.11it/s]
 46%|####6     | Permuting : 46/99 [00:00<00:00,  339.69it/s]
 59%|#####8    | Permuting : 58/99 [00:00<00:00,  342.92it/s]
 71%|#######   | Permuting : 70/99 [00:00<00:00,  345.35it/s]
 83%|########2 | Permuting : 82/99 [00:00<00:00,  347.02it/s]
 96%|#########5| Permuting : 95/99 [00:00<00:00,  352.72it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  351.73it/s]
Step-down-in-jumps iteration #1 found 0 clusters to exclude from subsequent iterations
Using a threshold of -1.713872
stat_fun(H1): min=-3.754759 max=3.360704
Running initial clustering …
Found 80 clusters

  0%|          | Permuting : 0/99 [00:00<?,       ?it/s]
 11%|#1        | Permuting : 11/99 [00:00<00:00,  324.50it/s]
 23%|##3       | Permuting : 23/99 [00:00<00:00,  340.39it/s]
 36%|###6      | Permuting : 36/99 [00:00<00:00,  355.52it/s]
 49%|####9     | Permuting : 49/99 [00:00<00:00,  363.37it/s]
 62%|######1   | Permuting : 61/99 [00:00<00:00,  361.53it/s]
 74%|#######3  | Permuting : 73/99 [00:00<00:00,  360.15it/s]
 86%|########5 | Permuting : 85/99 [00:00<00:00,  359.29it/s]
 99%|#########8| Permuting : 98/99 [00:00<00:00,  363.13it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  362.04it/s]
Step-down-in-jumps iteration #1 found 0 clusters to exclude from subsequent iterations
No baseline correction applied
Using a threshold of 1.713872
stat_fun(H1): min=-4.992503 max=5.416450
Running initial clustering …
Found 103 clusters

  0%|          | Permuting : 0/99 [00:00<?,       ?it/s]
 11%|#1        | Permuting : 11/99 [00:00<00:00,  324.62it/s]
 24%|##4       | Permuting : 24/99 [00:00<00:00,  355.80it/s]
 36%|###6      | Permuting : 36/99 [00:00<00:00,  355.84it/s]
 47%|####7     | Permuting : 47/99 [00:00<00:00,  347.83it/s]
 61%|######    | Permuting : 60/99 [00:00<00:00,  356.11it/s]
 74%|#######3  | Permuting : 73/99 [00:00<00:00,  361.57it/s]
 85%|########4 | Permuting : 84/99 [00:00<00:00,  355.56it/s]
 98%|#########7| Permuting : 97/99 [00:00<00:00,  359.99it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  359.60it/s]
Step-down-in-jumps iteration #1 found 1 cluster to exclude from subsequent iterations

  0%|          | Permuting : 0/99 [00:00<?,       ?it/s]
 11%|#1        | Permuting : 11/99 [00:00<00:00,  324.71it/s]
 23%|##3       | Permuting : 23/99 [00:00<00:00,  340.35it/s]
 35%|###5      | Permuting : 35/99 [00:00<00:00,  345.57it/s]
 47%|####7     | Permuting : 47/99 [00:00<00:00,  348.06it/s]
 61%|######    | Permuting : 60/99 [00:00<00:00,  356.23it/s]
 74%|#######3  | Permuting : 73/99 [00:00<00:00,  361.61it/s]
 85%|########4 | Permuting : 84/99 [00:00<00:00,  355.66it/s]
 98%|#########7| Permuting : 97/99 [00:00<00:00,  360.00it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  360.56it/s]
Step-down-in-jumps iteration #2 found 0 additional clusters to exclude from subsequent iterations
Using a threshold of -1.713872
stat_fun(H1): min=-4.992503 max=5.416450
Running initial clustering …
Found 67 clusters

  0%|          | Permuting : 0/99 [00:00<?,       ?it/s]
 11%|#1        | Permuting : 11/99 [00:00<00:00,  324.11it/s]
 23%|##3       | Permuting : 23/99 [00:00<00:00,  340.17it/s]
 36%|###6      | Permuting : 36/99 [00:00<00:00,  355.57it/s]
 48%|####8     | Permuting : 48/99 [00:00<00:00,  355.46it/s]
 61%|######    | Permuting : 60/99 [00:00<00:00,  355.44it/s]
 73%|#######2  | Permuting : 72/99 [00:00<00:00,  355.39it/s]
 85%|########4 | Permuting : 84/99 [00:00<00:00,  355.45it/s]
 97%|#########6| Permuting : 96/99 [00:00<00:00,  355.41it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  355.88it/s]
Step-down-in-jumps iteration #1 found 0 clusters to exclude from subsequent iterations
No baseline correction applied
Using a threshold of 1.713872
stat_fun(H1): min=-6.044340 max=4.070444
Running initial clustering …
Found 92 clusters

  0%|          | Permuting : 0/99 [00:00<?,       ?it/s]
 11%|#1        | Permuting : 11/99 [00:00<00:00,  323.72it/s]
 23%|##3       | Permuting : 23/99 [00:00<00:00,  339.96it/s]
 35%|###5      | Permuting : 35/99 [00:00<00:00,  345.13it/s]
 48%|####8     | Permuting : 48/99 [00:00<00:00,  355.87it/s]
 61%|######    | Permuting : 60/99 [00:00<00:00,  355.85it/s]
 73%|#######2  | Permuting : 72/99 [00:00<00:00,  355.78it/s]
 85%|########4 | Permuting : 84/99 [00:00<00:00,  355.63it/s]
 97%|#########6| Permuting : 96/99 [00:00<00:00,  355.51it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  355.54it/s]
Step-down-in-jumps iteration #1 found 1 cluster to exclude from subsequent iterations

  0%|          | Permuting : 0/99 [00:00<?,       ?it/s]
 11%|#1        | Permuting : 11/99 [00:00<00:00,  324.64it/s]
 23%|##3       | Permuting : 23/99 [00:00<00:00,  340.37it/s]
 35%|###5      | Permuting : 35/99 [00:00<00:00,  345.68it/s]
 47%|####7     | Permuting : 47/99 [00:00<00:00,  348.41it/s]
 60%|#####9    | Permuting : 59/99 [00:00<00:00,  350.00it/s]
 73%|#######2  | Permuting : 72/99 [00:00<00:00,  356.43it/s]
 84%|########3 | Permuting : 83/99 [00:00<00:00,  351.33it/s]
 96%|#########5| Permuting : 95/99 [00:00<00:00,  351.89it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  353.81it/s]
Step-down-in-jumps iteration #2 found 0 additional clusters to exclude from subsequent iterations
Using a threshold of -1.713872
stat_fun(H1): min=-6.044340 max=4.070444
Running initial clustering …
Found 51 clusters

  0%|          | Permuting : 0/99 [00:00<?,       ?it/s]
 11%|#1        | Permuting : 11/99 [00:00<00:00,  324.48it/s]
 23%|##3       | Permuting : 23/99 [00:00<00:00,  339.86it/s]
 36%|###6      | Permuting : 36/99 [00:00<00:00,  355.62it/s]
 47%|####7     | Permuting : 47/99 [00:00<00:00,  347.49it/s]
 60%|#####9    | Permuting : 59/99 [00:00<00:00,  349.26it/s]
 71%|#######   | Permuting : 70/99 [00:00<00:00,  344.72it/s]
 83%|########2 | Permuting : 82/99 [00:00<00:00,  346.52it/s]
 95%|#########4| Permuting : 94/99 [00:00<00:00,  347.88it/s]
100%|##########| Permuting : 99/99 [00:00<00:00,  348.59it/s]
Step-down-in-jumps iteration #1 found 0 clusters to exclude from subsequent iterations
No baseline correction applied

Similar to Epochs objects, we can also export data from EpochsTFR and AverageTFR objects to a Pandas DataFrame. By default, the time column of the exported data frame is in milliseconds. Here, to be consistent with the time-frequency plots, we want to keep it in seconds, which we can achieve by setting time_format=None:

df = tfr.to_data_frame(time_format=None)
df.head()
time freq epoch condition C3 Cz C4
0 -1.0000 2.0 0 feet -0.473093 -0.474571 -0.764021
1 -0.9875 2.0 0 feet -0.491659 -0.480088 -0.762445
2 -0.9750 2.0 0 feet -0.500872 -0.469376 -0.749421
3 -0.9625 2.0 0 feet -0.500605 -0.449373 -0.728686
4 -0.9500 2.0 0 feet -0.515911 -0.443439 -0.719536


This allows us to use additional plotting functions like seaborn.lineplot() to plot confidence bands:

df = tfr.to_data_frame(time_format=None, long_format=True)

# Map to frequency bands:
freq_bounds = {'_': 0,
               'delta': 3,
               'theta': 7,
               'alpha': 13,
               'beta': 35,
               'gamma': 140}
df['band'] = pd.cut(df['freq'], list(freq_bounds.values()),
                    labels=list(freq_bounds)[1:])

# Filter to retain only relevant frequency bands:
freq_bands_of_interest = ['delta', 'theta', 'alpha', 'beta']
df = df[df.band.isin(freq_bands_of_interest)]
df['band'] = df['band'].cat.remove_unused_categories()

# Order channels for plotting:
df['channel'] = df['channel'].cat.reorder_categories(('C3', 'Cz', 'C4'),
                                                     ordered=True)

g = sns.FacetGrid(df, row='band', col='channel', margin_titles=True)
g.map(sns.lineplot, 'time', 'value', 'condition', n_boot=10)
axline_kw = dict(color='black', linestyle='dashed', linewidth=0.5, alpha=0.5)
g.map(plt.axhline, y=0, **axline_kw)
g.map(plt.axvline, x=0, **axline_kw)
g.set(ylim=(None, 1.5))
g.set_axis_labels("Time (s)", "ERDS (%)")
g.set_titles(col_template="{col_name}", row_template="{row_name}")
g.add_legend(ncol=2, loc='lower center')
g.fig.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.08)
C3, Cz, C4
Converting "condition" to "category"...
Converting "epoch" to "category"...
Converting "channel" to "category"...
Converting "ch_type" to "category"...

Having the data as a DataFrame also facilitates subsetting, grouping, and other transforms. Here, we use seaborn to plot the average ERDS in the motor imagery interval as a function of frequency band and imagery condition:

df_mean = (df.query('time > 1')
             .groupby(['condition', 'epoch', 'band', 'channel'])[['value']]
             .mean()
             .reset_index())

g = sns.FacetGrid(df_mean, col='condition', col_order=['hands', 'feet'],
                  margin_titles=True)
g = (g.map(sns.violinplot, 'channel', 'value', 'band', n_boot=10,
           palette='deep', order=['C3', 'Cz', 'C4'],
           hue_order=freq_bands_of_interest,
           linewidth=0.5).add_legend(ncol=4, loc='lower center'))

g.map(plt.axhline, **axline_kw)
g.set_axis_labels("", "ERDS (%)")
g.set_titles(col_template="{col_name}", row_template="{row_name}")
g.fig.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.3)
hands, feet

References#

Total running time of the script: ( 0 minutes 30.877 seconds)

Estimated memory usage: 149 MB

Gallery generated by Sphinx-Gallery

On this page