Skip to content

plots

Plot EMG signals in time and frequency.

PSD axes are labelled in mV^2/Hz, which assumes the data is in mV.

plot_ch

plot_ch(data: ndarray, timestamps: ndarray, delta: Optional[int] = 5, ax: Optional[Axes] = None, palette_name: Optional[str] = 'viridis', **kwarg: Optional[Union[str, int, float]]) -> plt.Axes

Plot all channels stacked vertically in a single axes.

Each channel is shifted up by max(data) / delta times its index. Every fifth channel is labelled on the y axis.

Parameters:

Name Type Description Default
data ndarray

Float data with shape (samples, chs).

required
timestamps ndarray

Time of each sample in seconds, with shape (samples,).

required
delta int

Divisor of the data maximum that sets the spacing between channels. Larger values bring channels closer. Default is 5.

5
ax Axes

Axes to plot on. Default is None, which creates a new figure.

None
palette_name str

Name of the seaborn palette used to colour the channels. Default is "viridis".

'viridis'
**kwarg Optional[Union[str, int, float]]

Additional keyword arguments passed to matplotlib.axes.Axes.plot.

{}

Returns:

Type Description
Axes

plt.Axes: Axes where the data is plotted.

Source code in emg_tools/plots.py
25
26
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
def plot_ch(
    data: np.ndarray,
    timestamps: np.ndarray,
    delta: Optional[int] = 5,
    ax: Optional[plt.Axes] = None,
    palette_name: Optional[str] = "viridis",
    **kwarg: Optional[Union[str, int, float]]
    )-> plt.Axes:

    """Plot all channels stacked vertically in a single axes.

    Each channel is shifted up by `max(data) / delta` times its index. Every fifth
    channel is labelled on the y axis.

    Args:
        data (np.ndarray): Float data with shape (samples, chs).
        timestamps (np.ndarray): Time of each sample in seconds, with shape (samples,).
        delta (int, optional): Divisor of the data maximum that sets the spacing
            between channels. Larger values bring channels closer. Default is 5.
        ax (plt.Axes, optional): Axes to plot on. Default is None, which creates a
            new figure.
        palette_name (str, optional): Name of the seaborn palette used to colour
            the channels. Default is "viridis".
        **kwarg: Additional keyword arguments passed to `matplotlib.axes.Axes.plot`.

    Returns:
        plt.Axes: Axes where the data is plotted.
    """

    # Data size
    chs = data.shape[1]

    # Compute channel offset
    max_val = np.nanmax(data)
    offset = max_val/delta

    # Apply offset to signals
    data_plot = copy(data)
    data_plot += range(0,chs) * offset

    # Plot signals
    if ax is None:
        _, ax = plt.subplots()

    # Create color palette and assign it to the axis cycle
    color_palette = sns.color_palette(palette_name, chs).as_hex()
    ax.set_prop_cycle(color=color_palette)

    ax.plot(timestamps, data_plot, **kwarg)
    ax.margins(0) # padding for each limit of the axis
    ax.set_xlabel('Time (s)')
    ax.set_ylabel('Channels')
    ax.grid(True, axis='x')
    ch_ticks = np.linspace(0, (chs -1) * offset, chs)
    sel_chs = np.arange(0, chs, 5)
    ax.set_yticks(ch_ticks[sel_chs], sel_chs)

    return ax

plot_ch_map

plot_ch_map(values: ndarray, ch_map: ndarray, bad_ch: Optional[ndarray] = None, ax: Optional[Axes] = None, palette_name: Optional[str] = 'viridis', cbar_label: Optional[str] = None, **kwarg: Optional[Union[str, int, float]]) -> plt.Axes

Plot one value per channel on the electrode grid, annotated with channel numbers.

Parameters:

Name Type Description Default
values ndarray

Value per channel with shape (channels,).

required
ch_map ndarray

Channel map with shape (rows, cols). Empty cells (-1) are left blank.

required
bad_ch ndarray

Channels outlined in red. Default is None.

None
ax Axes

Axes to plot the map. Default is None.

None
palette_name str

Name of the colormap. Default is "viridis".

'viridis'
cbar_label str

Colorbar label. Default is None.

None
**kwarg Optional[Union[str, int, float]]

Additional keyword arguments to be passed to the heatmap function of seaborn.

{}

Returns:

Type Description
Axes

plt.Axes: Axes where the map is plotted.

Source code in emg_tools/plots.py
 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
def plot_ch_map(
    values: np.ndarray,
    ch_map: np.ndarray,
    bad_ch: Optional[np.ndarray] = None,
    ax: Optional[plt.Axes] = None,
    palette_name: Optional[str] = "viridis",
    cbar_label: Optional[str] = None,
    **kwarg: Optional[Union[str, int, float]]
) -> plt.Axes:

    """Plot one value per channel on the electrode grid, annotated with channel
    numbers.

    Args:
        values (np.ndarray): Value per channel with shape (channels,).
        ch_map (np.ndarray): Channel map with shape (rows, cols). Empty cells
            (-1) are left blank.
        bad_ch (np.ndarray, optional): Channels outlined in red. Default is None.
        ax (plt.Axes, optional): Axes to plot the map. Default is None.
        palette_name (str, optional): Name of the colormap. Default is "viridis".
        cbar_label (str, optional): Colorbar label. Default is None.
        **kwarg: Additional keyword arguments to be passed to the `heatmap`
            function of seaborn.

    Returns:
        plt.Axes: Axes where the map is plotted.
    """

    if ax is None:
        _, ax = plt.subplots()

    # Arrange values on the grid, leaving empty cells blank
    values_map = np.where(ch_map >= 0, values[ch_map], np.nan)

    sns.heatmap(
        values_map, annot=ch_map, fmt="d", annot_kws={"fontsize": 6},
        cmap=palette_name, square=True, xticklabels=False, yticklabels=False,
        cbar_kws={"label": cbar_label}, ax=ax, **kwarg
    )

    # Outline bad channels
    if bad_ch is not None:
        for row, col in np.argwhere(np.isin(ch_map, bad_ch)):
            ax.add_patch(Rectangle((col, row), 1, 1, fill=False, edgecolor="red", lw=1.5))

    return ax

plot_psd

plot_psd(data: ndarray, fs: Optional[int] = 2048, ax: Optional[Axes] = None, palette_name: Optional[str] = 'viridis', log_scale: Optional[bool] = False, **kwarg: Optional[Union[str, int, float]]) -> plt.Axes

Plot the periodogram PSD of each channel as one line per channel.

Parameters:

Name Type Description Default
data ndarray

Input data with shape (samples, chs).

required
fs int

Sampling frequency in Hz. Default is 2048.

2048
ax Axes

Axes to plot on. Default is None, which creates a new figure.

None
palette_name str

Name of the seaborn palette used to colour the channels. Default is "viridis".

'viridis'
log_scale bool

If True, the PSD axis is logarithmic. Default is False.

False
**kwarg Optional[Union[str, int, float]]

Additional keyword arguments passed to matplotlib.axes.Axes.plot.

{}

Returns:

Type Description
Axes

plt.Axes: Axes where the PSD is plotted.

Source code in emg_tools/plots.py
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
def plot_psd(
    data: np.ndarray,
    fs: Optional[int] = 2048,
    ax: Optional[plt.Axes] = None,
    palette_name: Optional[str] = "viridis",
    log_scale: Optional[bool] = False,
    **kwarg: Optional[Union[str, int, float]]
) -> plt.Axes:

    """Plot the periodogram PSD of each channel as one line per channel.

    Args:
        data (np.ndarray): Input data with shape (samples, chs).
        fs (int, optional): Sampling frequency in Hz. Default is 2048.
        ax (plt.Axes, optional): Axes to plot on. Default is None, which creates a
            new figure.
        palette_name (str, optional): Name of the seaborn palette used to colour
            the channels. Default is "viridis".
        log_scale (bool, optional): If True, the PSD axis is logarithmic. Default
            is False.
        **kwarg: Additional keyword arguments passed to `matplotlib.axes.Axes.plot`.

    Returns:
        plt.Axes: Axes where the PSD is plotted.
    """

    # Initialise variables
    chs = data.shape[1]

    # Define axis if None
    if ax is None:
        _, ax = plt.subplots(1, 1, figsize=(10,5), layout='tight')

    # Create color palette and assign it to the axis cycle
    color_palette = sns.color_palette(palette_name, chs).as_hex()
    ax.set_prop_cycle(color=color_palette)

    # Plot PSD
    psd, xf = get_psd(data, fs)

    if log_scale:
        ax.semilogy(xf, psd, **kwarg)
        ax.set_ylabel('PSD (mV^2/Hz)')
    else:
        ax.plot(xf, psd, **kwarg)
        ax.set_ylabel('PSD (mV^2/Hz)')
    ax.set_xlabel('Frequency (Hz)')

    return ax

plot_psd_map

plot_psd_map(data: ndarray, fs: Optional[int] = 2048, ax: Optional[Axes] = None, log_scale: Optional[bool] = False, eps: Optional[float] = None, palette_name: Optional[str] = 'viridis', **kwarg: Optional[Union[str, int, float]]) -> plt.Axes

Plot the periodogram PSD as a heatmap of frequency against channel.

Parameters:

Name Type Description Default
data ndarray

Input data with shape (samples, chs).

required
fs int

Sampling frequency in Hz. Default is 2048.

2048
ax Axes

Axes to plot on. Default is None, which creates a new figure.

None
log_scale bool

If True, the colour scale is logarithmic. Default is False.

False
eps float

Lower limit of the log colour scale, to avoid log(0). Only used if log_scale is True. Default is None, which uses the smallest positive PSD value.

None
palette_name str

Name of the matplotlib colormap. Default is "viridis".

'viridis'
**kwarg Optional[Union[str, int, float]]

Additional keyword arguments passed to matplotlib.axes.Axes.pcolormesh.

{}

Returns:

Type Description
Axes

plt.Axes: Axes where the PSD is plotted.

Source code in emg_tools/plots.py
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
237
238
239
240
241
242
def plot_psd_map(
    data: np.ndarray,
    fs: Optional[int] = 2048,
    ax: Optional[plt.Axes] = None,
    log_scale: Optional[bool] = False,
    eps: Optional[float] = None,
    palette_name: Optional[str] = "viridis",
    **kwarg: Optional[Union[str, int, float]]
) -> plt.Axes:

    """Plot the periodogram PSD as a heatmap of frequency against channel.

    Args:
        data (np.ndarray): Input data with shape (samples, chs).
        fs (int, optional): Sampling frequency in Hz. Default is 2048.
        ax (plt.Axes, optional): Axes to plot on. Default is None, which creates a
            new figure.
        log_scale (bool, optional): If True, the colour scale is logarithmic. Default
            is False.
        eps (float, optional): Lower limit of the log colour scale, to avoid log(0).
            Only used if log_scale is True. Default is None, which uses the smallest
            positive PSD value.
        palette_name (str, optional): Name of the matplotlib colormap. Default is
            "viridis".
        **kwarg: Additional keyword arguments passed to
            `matplotlib.axes.Axes.pcolormesh`.

    Returns:
        plt.Axes: Axes where the PSD is plotted.
    """

    # Initialise variables
    samples, chs = data.shape

    # Plot PSD
    psd, xf = get_psd(data, fs)

    # Plot PSD
    if ax is None:
        _, ax = plt.subplots(1, 1, figsize=(10,5), layout='tight')
    if log_scale:
        if eps is None:
            eps = _min_positive(psd)
        norm=colors.LogNorm(vmin=eps, vmax=psd.max())
        cbar_label = 'PSD (mV^2/Hz)'
    else:
        norm=None
        cbar_label = 'PSD (mV^2/Hz)'
    im = ax.pcolormesh(
        np.arange(chs), xf, psd,
        shading='gouraud', cmap=palette_name, norm=norm,
        **kwarg
        )
    cbar = ax.figure.colorbar(im, ax=ax)
    cbar.set_label(cbar_label, rotation=90)
    ax.grid(False)
    ax.set_ylabel('Frequency (Hz)')
    ax.set_xlabel('Channels')

    return ax

plot_comp_spectrogram

plot_comp_spectrogram(data: ndarray, fs: Optional[int] = 2048, ax: Optional[Union[Axes, ndarray]] = None, log_scale: Optional[bool] = False, eps: Optional[float] = None, palette_name: Optional[str] = 'viridis', **kwarg: Optional[Union[str, int, float]]) -> np.ndarray

Compute the spectrogram of each channel and plot it with plot_spectrogram.

Parameters:

Name Type Description Default
data ndarray

Input data with shape (samples, chs) or (samples,).

required
fs int

Sampling frequency in Hz. Default is 2048.

2048
ax Axes or ndarray

Axes to plot on, one per channel. Default is None, which creates one row of axes per channel.

None
log_scale bool

If True, the colour scale is logarithmic. Default is False.

False
eps float

Lower limit of the colour scale. Default is None, which uses the smallest positive value in log scale and the minimum otherwise.

None
palette_name str

Name of the matplotlib colormap. Default is "viridis".

'viridis'
**kwarg Optional[Union[str, int, float]]

Additional keyword arguments passed to matplotlib.axes.Axes.pcolormesh.

{}

Returns:

Type Description
ndarray

np.ndarray: Array of axes where the spectrogram of each channel is plotted.

Source code in emg_tools/plots.py
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
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
def plot_comp_spectrogram(
    data: np.ndarray,
    fs: Optional[int] = 2048,
    ax: Optional[Union[plt.Axes, np.ndarray]] = None,
    log_scale: Optional[bool] = False,
    eps: Optional[float] = None,
    palette_name: Optional[str] = "viridis",
    **kwarg: Optional[Union[str, int, float]]
) -> np.ndarray:

    """Compute the spectrogram of each channel and plot it with `plot_spectrogram`.

    Args:
        data (np.ndarray): Input data with shape (samples, chs) or (samples,).
        fs (int, optional): Sampling frequency in Hz. Default is 2048.
        ax (plt.Axes or np.ndarray, optional): Axes to plot on, one per channel.
            Default is None, which creates one row of axes per channel.
        log_scale (bool, optional): If True, the colour scale is logarithmic. Default
            is False.
        eps (float, optional): Lower limit of the colour scale. Default is None, which
            uses the smallest positive value in log scale and the minimum otherwise.
        palette_name (str, optional): Name of the matplotlib colormap. Default is
            "viridis".
        **kwarg: Additional keyword arguments passed to
            `matplotlib.axes.Axes.pcolormesh`.

    Returns:
        np.ndarray: Array of axes where the spectrogram of each channel is plotted.
    """

    # Compute spectrogram (one sided) with shape (freqs, chs, times)
    f, t, sxx = signal.spectrogram(data, fs, axis=0)

    # Rearrange to (freqs, times, chs)
    if sxx.ndim == 3:
        sxx = np.moveaxis(sxx, 1, -1)

    return plot_spectrogram(
        f, t, sxx, ax=ax, palette_name=palette_name,
        log_scale=log_scale, eps=eps, **kwarg
    )

plot_spectrogram

plot_spectrogram(f: ndarray, t: ndarray, sxx: ndarray, ax: Optional[Union[Axes, ndarray]] = None, palette_name: Optional[str] = 'magma', log_scale: Optional[bool] = False, eps: Optional[float] = None, **kwarg: Optional[Union[str, int, float]]) -> np.ndarray

Plot a precomputed spectrogram, one axes per signal.

All signals share the same colour scale.

Parameters:

Name Type Description Default
f ndarray

Frequencies in Hz, with shape (freqs,).

required
t ndarray

Times in seconds, with shape (times,).

required
sxx ndarray

Spectrogram with shape (freqs, times, signals), or (freqs, times) for a single signal.

required
ax Axes or ndarray

Axes to plot on, one per signal. Default is None, which creates one row of axes per signal.

None
palette_name str

Name of the matplotlib colormap. Default is "magma".

'magma'
log_scale bool

If True, the colour scale is logarithmic. Default is False.

False
eps float

Lower limit of the colour scale. Default is None, which uses the smallest positive value in log scale and the minimum otherwise.

None
**kwarg Optional[Union[str, int, float]]

Additional keyword arguments passed to matplotlib.axes.Axes.pcolormesh.

{}

Returns:

Type Description
ndarray

np.ndarray: Array of axes where the spectrogram of each signal is plotted.

Source code in emg_tools/plots.py
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
def plot_spectrogram(
    f: np.ndarray,
    t: np.ndarray,
    sxx: np.ndarray,
    ax: Optional[Union[plt.Axes, np.ndarray]] = None,
    palette_name: Optional[str] = "magma",
    log_scale: Optional[bool] = False,
    eps: Optional[float] = None,
    **kwarg: Optional[Union[str, int, float]]
) -> np.ndarray:

    """Plot a precomputed spectrogram, one axes per signal.

    All signals share the same colour scale.

    Args:
        f (np.ndarray): Frequencies in Hz, with shape (freqs,).
        t (np.ndarray): Times in seconds, with shape (times,).
        sxx (np.ndarray): Spectrogram with shape (freqs, times, signals), or
            (freqs, times) for a single signal.
        ax (plt.Axes or np.ndarray, optional): Axes to plot on, one per signal.
            Default is None, which creates one row of axes per signal.
        palette_name (str, optional): Name of the matplotlib colormap. Default is
            "magma".
        log_scale (bool, optional): If True, the colour scale is logarithmic. Default
            is False.
        eps (float, optional): Lower limit of the colour scale. Default is None, which
            uses the smallest positive value in log scale and the minimum otherwise.
        **kwarg: Additional keyword arguments passed to
            `matplotlib.axes.Axes.pcolormesh`.

    Returns:
        np.ndarray: Array of axes where the spectrogram of each signal is plotted.
    """

    # Normalise spectrogram if log scale
    if log_scale:
        if eps is None:
            eps = _min_positive(sxx)
        norm=colors.LogNorm(vmin=eps, vmax=sxx.max())
        cbar_label = 'PSD (mV^2/Hz)'
    else:
        if eps is None:
            eps = sxx.min()
        norm=colors.Normalize(vmin=eps, vmax=sxx.max())
        cbar_label = 'PSD (mV^2/Hz)'

    # Plot spectrogram per signal
    if len(sxx.shape) == 2:
        sxx = np.expand_dims(sxx, axis=-1)
    nsig = sxx.shape[-1]

    if ax is None:
        cols = 1
        rows = np.round(nsig/cols).astype(int)

        fig, ax = plt.subplots(
            rows, cols, figsize=(12, 6),
            sharex=True, sharey=True, layout='constrained', squeeze=False
        )
    ax = np.atleast_1d(ax).flatten()

    for i in range(nsig):
        # Plot spectrogram
        im = ax[i].pcolormesh(
            t, f, sxx[:,:,i],
            shading='gouraud', cmap=palette_name, norm=norm,
            **kwarg
        )
        cbar = ax[i].figure.colorbar(im, ax=ax[i])
        cbar.set_label(cbar_label, rotation=90)
        ax[i].set_ylabel('Frequency (Hz)')
        ax[i].set_xlabel('Time (s)')
        ax[i].set_title(f'Channel {i}')

    return ax