mne.time_frequency.EpochsSpectrum#

class mne.time_frequency.EpochsSpectrum(inst, method, fmin, fmax, tmin, tmax, picks, proj, *, n_jobs, verbose=None, **method_kw)[source]#

Data object for spectral representations of epoched data.

Warning

The preferred means of creating Spectrum objects from Epochs is via the instance method mne.Epochs.compute_psd(). Direct class instantiation is not supported.

Parameters:
instinstance of Epochs

The data from which to compute the frequency spectrum.

method'welch' | 'multitaper'

Spectral estimation method. 'welch' uses Welch’s method[1], 'multitaper' uses DPSS tapers[2].

fmin, fmaxfloat

The lower- and upper-bound on frequencies of interest. Default is fmin=0, fmax=np.inf (spans all frequencies present in the data).

tmin, tmaxfloat | None

First and last times to include, in seconds. None uses the first or last time present in the data. Default is tmin=None, tmax=None (all times).

picksstr | array_like | slice | None

Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g., ['meg', 'eeg']) will pick channels of those types, channel name strings (e.g., ['MEG0111', 'MEG2623'] will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick good data channels (excluding reference MEG channels). Note that channels in info['bads'] will be included if their names or indices are explicitly provided.

projbool

Whether to apply SSP projection vectors before spectral estimation. Default is False.

n_jobsint | None

The number of jobs to run in parallel. If -1, it is set to the number of CPU cores. Requires the joblib package. None (default) is a marker for ‘unset’ that will be interpreted as n_jobs=1 (sequential execution) unless the call is performed under a joblib.parallel_backend() context manager that sets another value for n_jobs.

verbosebool | str | int | None

Control verbosity of the logging output. If None, use the default verbosity level. See the logging documentation and mne.verbose() for details. Should only be passed as a keyword argument.

**method_kw

Additional keyword arguments passed to the spectral estimation function (e.g., n_fft, n_overlap, n_per_seg, average, window for Welch method, or bandwidth, adaptive, low_bias, normalization for multitaper method). See psd_array_welch() and psd_array_multitaper() for details.

References

Attributes:
ch_nameslist

The channel names.

freqsarray

Frequencies at which the amplitude, power, or fourier coefficients have been computed.

infomne.Info

The mne.Info object with information about the sensors and methods of measurement.

methodstr

The method used to compute the spectrum (‘welch’ or ‘multitaper’).

Methods

__contains__(ch_type)

Check channel type membership.

__getitem__(item)

Subselect epochs from an EpochsSpectrum.

__iter__()

Facilitate iteration over epochs.

__len__()

Return the number of epochs.

add_channels(add_list[, force_update_info])

Append new channels to the instance.

add_reference_channels(ref_channels)

Add reference channels to data that consists of all zeros.

average([method])

Average the spectra across epochs.

copy()

Return copy of the Spectrum instance.

drop_channels(ch_names[, on_missing])

Drop channel(s).

get_channel_types([picks, unique, only_data_chs])

Get a list of channel type for each channel.

get_data([picks, exclude, fmin, fmax, ...])

Get spectrum data in NumPy array format.

next([return_event_id])

Iterate over epoch data.

pick(picks[, exclude, verbose])

Pick a subset of channels.

pick_channels(ch_names[, ordered, verbose])

Pick some channels.

pick_types([meg, eeg, stim, eog, ecg, emg, ...])

Pick some channels by type and names.

plot(*[, picks, average, dB, amplitude, ...])

Plot power or amplitude spectra.

plot_topo(*[, dB, layout, color, ...])

Plot power spectral density, separately for each channel.

plot_topomap([bands, ch_type, normalize, ...])

Plot scalp topography of PSD for chosen frequency bands.

reorder_channels(ch_names)

Reorder channels.

save(fname, *[, overwrite, verbose])

Save spectrum data to disk (in HDF5 format).

to_data_frame([picks, index, copy, ...])

Export data in tabular structure as a pandas DataFrame.

units([latex])

Get the spectrum units for each channel type.

__contains__(ch_type)[source]#

Check channel type membership.

Parameters:
ch_typestr

Channel type to check for. Can be e.g. ‘meg’, ‘eeg’, ‘stim’, etc.

Returns:
inbool

Whether or not the instance contains the given channel type.

Examples

Channel type membership can be tested as:

>>> 'meg' in inst  
True
>>> 'seeg' in inst  
False
__getitem__(item)[source]#

Subselect epochs from an EpochsSpectrum.

Parameters:
itemint | slice | array_like | str

Access options are the same as for Epochs objects, see the docstring of mne.Epochs.__getitem__() for explanation.

Returns:
%(getitem_epochspectrum_return)s
__iter__()[source]#

Facilitate iteration over epochs.

This method resets the object iteration state to the first epoch.

Notes

This enables the use of this Python pattern:

>>> for epoch in epochs:  
>>>     print(epoch)  

Where epoch is given by successive outputs of mne.Epochs.next().

__len__()[source]#

Return the number of epochs.

Returns:
n_epochsint

The number of remaining epochs.

Notes

This function only works if bad epochs have been dropped.

Examples

This can be used as:

>>> epochs.drop_bad()  
>>> len(epochs)  
43
>>> len(epochs.events)  
43
add_channels(add_list, force_update_info=False)[source]#

Append new channels to the instance.

Parameters:
add_listlist

A list of objects to append to self. Must contain all the same type as the current object.

force_update_infobool

If True, force the info for objects to be appended to match the values in self. This should generally only be used when adding stim channels for which important metadata won’t be overwritten.

New in version 0.12.

Returns:
instinstance of Raw, Epochs, or Evoked

The modified instance.

See also

drop_channels

Notes

If self is a Raw instance that has been preloaded into a numpy.memmap instance, the memmap will be resized.

add_reference_channels(ref_channels)[source]#

Add reference channels to data that consists of all zeros.

Adds reference channels to data that were not included during recording. This is useful when you need to re-reference your data to different channels. These added channels will consist of all zeros.

Parameters:
ref_channelsstr | list of str

Name of the electrode(s) which served as the reference in the recording. If a name is provided, a corresponding channel is added and its data is set to 0. This is useful for later re-referencing.

Returns:
instinstance of Raw | Epochs | Evoked

The modified instance.

average(method='mean')[source]#

Average the spectra across epochs.

Parameters:
method‘mean’ | ‘median’ | callable()

How to aggregate spectra across epochs. If callable, must take a NumPy array of shape (n_epochs, n_channels, n_freqs) and return an array of shape (n_channels, n_freqs). Default is 'mean'.

Returns:
spectruminstance of Spectrum

The aggregated spectrum object.

Examples using average:

Frequency and time-frequency sensor analysis

Frequency and time-frequency sensor analysis
property compensation_grade#

The current gradient compensation grade.

copy()[source]#

Return copy of the Spectrum instance.

Returns:
spectruminstance of Spectrum

A copy of the object.

drop_channels(ch_names, on_missing='raise')[source]#

Drop channel(s).

Parameters:
ch_namesiterable or str

Iterable (e.g. list) of channel name(s) or channel name to remove.

on_missing‘raise’ | ‘warn’ | ‘ignore’

Can be 'raise' (default) to raise an error, 'warn' to emit a warning, or 'ignore' to ignore when entries in ch_names are not present in the raw instance.

New in version 0.23.0.

Returns:
instinstance of Raw, Epochs, or Evoked

The modified instance.

Notes

New in version 0.9.0.

get_channel_types(picks=None, unique=False, only_data_chs=False)[source]#

Get a list of channel type for each channel.

Parameters:
picksstr | array_like | slice | None

Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g., ['meg', 'eeg']) will pick channels of those types, channel name strings (e.g., ['MEG0111', 'MEG2623'] will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick all channels. Note that channels in info['bads'] will be included if their names or indices are explicitly provided.

uniquebool

Whether to return only unique channel types. Default is False.

only_data_chsbool

Whether to ignore non-data channels. Default is False.

Returns:
channel_typeslist

The channel types.

get_data(picks=None, exclude='bads', fmin=0, fmax=inf, return_freqs=False)[source]#

Get spectrum data in NumPy array format.

Parameters:
picksstr | array_like | slice | None

Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g., ['meg', 'eeg']) will pick channels of those types, channel name strings (e.g., ['MEG0111', 'MEG2623'] will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick good data channels (excluding reference MEG channels). Note that channels in info['bads'] will be included if their names or indices are explicitly provided.

excludelist of str | ‘bads’

Channel names to exclude. If 'bads', channels in spectrum.info['bads'] are excluded; pass an empty list to plot all channels (including “bad” channels, if any).

fmin, fmaxfloat

The lower- and upper-bound on frequencies of interest. Default is fmin=0, fmax=np.inf (spans all frequencies present in the data).

return_freqsbool

Whether to return the frequency bin values for the requested frequency range. Default is False.

Returns:
dataarray

The requested data in a NumPy array.

freqsarray

The frequency values for the requested range. Only returned if return_freqs is True.

Examples using get_data:

The Spectrum and EpochsSpectrum classes: frequency-domain data

The Spectrum and EpochsSpectrum classes: frequency-domain data

Frequency-tagging: Basic analysis of an SSVEP/vSSR dataset

Frequency-tagging: Basic analysis of an SSVEP/vSSR dataset

Sleep stage classification from polysomnography (PSG) data

Sleep stage classification from polysomnography (PSG) data
property metadata#

Get the metadata.

next(return_event_id=False)[source]#

Iterate over epoch data.

Parameters:
return_event_idbool

If True, return both the epoch data and an event_id.

Returns:
epocharray of shape (n_channels, n_times)

The epoch data.

event_idint

The event id. Only returned if return_event_id is True.

pick(picks, exclude=(), *, verbose=None)[source]#

Pick a subset of channels.

Parameters:
picksstr | array_like | slice | None

Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g., ['meg', 'eeg']) will pick channels of those types, channel name strings (e.g., ['MEG0111', 'MEG2623'] will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick all channels. Note that channels in info['bads'] will be included if their names or indices are explicitly provided.

excludelist | str

Set of channels to exclude, only used when picking based on types (e.g., exclude=”bads” when picks=”meg”).

verbosebool | str | int | None

Control verbosity of the logging output. If None, use the default verbosity level. See the logging documentation and mne.verbose() for details. Should only be passed as a keyword argument.

New in version 0.24.0.

Returns:
instinstance of Raw, Epochs, or Evoked

The modified instance.

pick_channels(ch_names, ordered=False, *, verbose=None)[source]#

Pick some channels.

Parameters:
ch_nameslist

The list of channels to select.

orderedbool

If True (default False), ensure that the order of the channels in the modified instance matches the order of ch_names.

New in version 0.20.0.

verbosebool | str | int | None

Control verbosity of the logging output. If None, use the default verbosity level. See the logging documentation and mne.verbose() for details. Should only be passed as a keyword argument.

New in version 1.1.

Returns:
instinstance of Raw, Epochs, or Evoked

The modified instance.

Notes

The channel names given are assumed to be a set, i.e. the order does not matter. The original order of the channels is preserved. You can use reorder_channels to set channel order if necessary.

New in version 0.9.0.

pick_types(meg=False, eeg=False, stim=False, eog=False, ecg=False, emg=False, ref_meg='auto', *, misc=False, resp=False, chpi=False, exci=False, ias=False, syst=False, seeg=False, dipole=False, gof=False, bio=False, ecog=False, fnirs=False, csd=False, dbs=False, temperature=False, gsr=False, include=(), exclude='bads', selection=None, verbose=None)[source]#

Pick some channels by type and names.

Parameters:
megbool | str

If True include MEG channels. If string it can be ‘mag’, ‘grad’, ‘planar1’ or ‘planar2’ to select only magnetometers, all gradiometers, or a specific type of gradiometer.

eegbool

If True include EEG channels.

stimbool

If True include stimulus channels.

eogbool

If True include EOG channels.

ecgbool

If True include ECG channels.

emgbool

If True include EMG channels.

ref_megbool | str

If True include CTF / 4D reference channels. If ‘auto’, reference channels are included if compensations are present and meg is not False. Can also be the string options for the meg parameter.

miscbool

If True include miscellaneous analog channels.

respbool

If True include respiratory channels.

chpibool

If True include continuous HPI coil channels.

excibool

Flux excitation channel used to be a stimulus channel.

iasbool

Internal Active Shielding data (maybe on Triux only).

systbool

System status channel information (on Triux systems only).

seegbool

Stereotactic EEG channels.

dipolebool

Dipole time course channels.

gofbool

Dipole goodness of fit channels.

biobool

Bio channels.

ecogbool

Electrocorticography channels.

fnirsbool | str

Functional near-infrared spectroscopy channels. If True include all fNIRS channels. If False (default) include none. If string it can be ‘hbo’ (to include channels measuring oxyhemoglobin) or ‘hbr’ (to include channels measuring deoxyhemoglobin).

csdbool

EEG-CSD channels.

dbsbool

Deep brain stimulation channels.

temperaturebool

Temperature channels.

gsrbool

Galvanic skin response channels.

includelist of str

List of additional channels to include. If empty do not include any.

excludelist of str | str

List of channels to exclude. If ‘bads’ (default), exclude channels in info['bads'].

selectionlist of str

Restrict sensor channels (MEG, EEG, etc.) to this list of channel names.

verbosebool | str | int | None

Control verbosity of the logging output. If None, use the default verbosity level. See the logging documentation and mne.verbose() for details. Should only be passed as a keyword argument.

Returns:
instinstance of Raw, Epochs, or Evoked

The modified instance.

See also

pick_channels

Notes

New in version 0.9.0.

plot(*, picks=None, average=False, dB=True, amplitude='auto', xscale='linear', ci='sd', ci_alpha=0.3, color='black', alpha=None, spatial_colors=True, sphere=None, exclude='bads', axes=None, show=True)[source]#

Plot power or amplitude spectra.

Separate plots are drawn for each channel type. When the data have been processed with a bandpass, lowpass or highpass filter, dashed lines (╎) indicate the boundaries of the filter. The line noise frequency is also indicated with a dashed line (⋮). If average=False, the plot will be interactive, and click-dragging on the spectrum will generate a scalp topography plot for the chosen frequency range in a new figure.

Parameters:
picksstr | array_like | slice | None

Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g., ['meg', 'eeg']) will pick channels of those types, channel name strings (e.g., ['MEG0111', 'MEG2623'] will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick good data channels (excluding reference MEG channels). Note that channels in info['bads'] will be included if their names or indices are explicitly provided.

averagebool

Whether to average across channels before plotting. If True, interactive plotting of scalp topography is disabled, and parameters ci and ci_alpha control the style of the confidence band around the mean. Default is False.

dBbool

Whether to plot on a decibel-like scale. If True, plots 10 × log₁₀(spectral power).

amplitudebool | ‘auto’

Whether to plot an amplitude spectrum (True) or power spectrum (False). If 'auto', will plot a power spectrum when dB=True and an amplitude spectrum otherwise. Default is 'auto'.

xscale‘linear’ | ‘log’

Scale of the frequency axis. Default is 'linear'.

cifloat | ‘sd’ | ‘range’ | None

Type of confidence band drawn around the mean when average=True. If 'sd' the band spans ±1 standard deviation across channels. If 'range' the band spans the range across channels at each frequency. If a float, it indicates the (bootstrapped) confidence interval to display, and must satisfy 0 < ci <= 100. If None, no band is drawn. Default is sd.

ci_alphafloat

Opacity of the confidence band. Must satisfy 0 <= ci_alpha <= 1. Default is 0.3.

colorstr | tuple

A matplotlib-compatible color to use. Has no effect when spatial_colors=True.

alphafloat | None

Opacity of the spectrum line(s). If float, must satisfy 0 <= alpha <= 1. If None, opacity will be 1 when average=True and 0.1 when average=False. Default is None.

spatial_colorsbool

Whether to color spectrum lines by channel location. Ignored if average=True.

spherefloat | array_like | instance of ConductorModel | None | ‘auto’ | ‘eeglab’

The sphere parameters to use for the head outline. Can be array-like of shape (4,) to give the X/Y/Z origin and radius in meters, or a single float to give just the radius (origin assumed 0, 0, 0). Can also be an instance of a spherical ConductorModel to use the origin and radius from that object. If 'auto' the sphere is fit to digitization points. If 'eeglab' the head circle is defined by EEG electrodes 'Fpz', 'Oz', 'T7', and 'T8' (if 'Fpz' is not present, it will be approximated from the coordinates of 'Oz'). None (the default) is equivalent to 'auto' when enough extra digitization points are available, and (0, 0, 0, 0.095) otherwise.

New in version 0.20.

Changed in version 1.1: Added 'eeglab' option.

excludelist of str | ‘bads’

Channel names to exclude from being drawn. If 'bads', channels in spectrum.info['bads'] are excluded; pass an empty list to plot all channels (including “bad” channels, if any).

axesinstance of Axes | list of Axes | None

The axes to plot to. If None, a new Figure will be created with the correct number of axes. If Axes are provided (either as a single instance or a list of axes), the number of axes provided must match the length of bands.Default is None.

showbool

Show the figure if True.

Returns:
figinstance of matplotlib.figure.Figure

Figure with spectra plotted in separate subplots for each channel type.

Examples using plot:

Visualizing epoched data

Visualizing epoched data

Sleep stage classification from polysomnography (PSG) data

Sleep stage classification from polysomnography (PSG) data
plot_topo(*, dB=True, layout=None, color='w', fig_facecolor='k', axis_facecolor='k', axes=None, block=False, show=True)[source]#

Plot power spectral density, separately for each channel.

Parameters:
dBbool

Whether to plot on a decibel-like scale. If True, plots 10 × log₁₀(spectral power). Ignored if normalize=True.

layoutinstance of Layout | None

Layout instance specifying sensor positions (does not need to be specified for Neuromag data). If None (default), the layout is inferred from the data.

colorstr | tuple

A matplotlib-compatible color to use for the curves. Defaults to white.

fig_facecolorstr | tuple

A matplotlib-compatible color to use for the figure background. Defaults to black.

axis_facecolorstr | tuple

A matplotlib-compatible color to use for the axis background. Defaults to black.

axesinstance of Axes | list of Axes | None

The axes to plot to. If None, a new Figure will be created with the correct number of axes. If Axes are provided (either as a single instance or a list of axes), the number of axes provided must be length 1 (for efficiency, subplots for each channel are simulated within a single Axes object).Default is None.

blockbool

Whether to halt program execution until the figure is closed. May not work on all systems / platforms. Defaults to False.

showbool

Show the figure if True.

Returns:
figinstance of matplotlib.figure.Figure

Figure distributing one image per channel across sensor topography.

plot_topomap(bands=None, ch_type=None, *, normalize=False, agg_fun=None, dB=False, sensors=True, show_names=False, mask=None, mask_params=None, contours=6, outlines='head', sphere=None, image_interp='cubic', extrapolate='auto', border='mean', res=64, size=1, cmap=None, vlim=(None, None), cnorm=None, colorbar=True, cbar_fmt='auto', units=None, axes=None, show=True)[source]#

Plot scalp topography of PSD for chosen frequency bands.

Parameters:
bandsNone | dict | list of tuple

The frequencies or frequency ranges to plot. If a dict, keys will be used as subplot titles and values should be either a single frequency (e.g., {'presentation rate': 6.5}) or a length-two sequence of lower and upper frequency band edges (e.g., {'theta': (4, 8)}). If a single frequency is provided, the plot will show the frequency bin that is closest to the requested value. If None (the default), expands to:

bands = {'Delta (0-4 Hz)': (0, 4), 'Theta (4-8 Hz)': (4, 8),
         'Alpha (8-12 Hz)': (8, 12), 'Beta (12-30 Hz)': (12, 30),
         'Gamma (30-45 Hz)': (30, 45)}

Note

For backwards compatibility, tuples of length 2 or 3 are also accepted, where the last element of the tuple is the subplot title and the other entries are frequency values (a single value or band edges). New code should use dict or None.

Changed in version 1.2: Allow passing a dict and discourage passing tuples.

ch_type‘mag’ | ‘grad’ | ‘planar1’ | ‘planar2’ | ‘eeg’ | None

The channel type to plot. For 'grad', the gradiometers are collected in pairs and the mean for each pair is plotted. If None the first available channel type from order shown above is used. Defaults to None.

normalizebool

If True, each band will be divided by the total power. Defaults to False.

agg_funcallable()

The function used to aggregate over frequencies. Defaults to numpy.sum() if normalize=True, else numpy.mean().

dBbool

Whether to plot on a decibel-like scale. If True, plots 10 × log₁₀(spectral power) following the application of agg_fun. Ignored if normalize=True.

sensorsbool | str

Whether to add markers for sensor locations. If str, should be a valid matplotlib format string (e.g., 'r+' for red plusses, see the Notes section of plot()). If True (the default), black circles will be used.

show_namesbool | callable()

If True, show channel names next to each sensor marker. If callable, channel names will be formatted using the callable; e.g., to delete the prefix ‘MEG ‘ from all channel names, pass the function lambda x: x.replace('MEG ', ''). If mask is not None, only non-masked sensor names will be shown.

maskndarray of bool, shape (n_channels, n_times) | None

Array indicating channel-time combinations to highlight with a distinct plotting style (useful for, e.g. marking which channels at which times a statistical test of the data reaches significance). Array elements set to True will be plotted with the parameters given in mask_params. Defaults to None, equivalent to an array of all False elements.

mask_paramsdict | None

Additional plotting parameters for plotting significant sensors. Default (None) equals:

dict(marker='o', markerfacecolor='w', markeredgecolor='k',
        linewidth=0, markersize=4)
contoursint | array_like

The number of contour lines to draw. If 0, no contours will be drawn. If a positive integer, that number of contour levels are chosen using the matplotlib tick locator (may sometimes be inaccurate, use array for accuracy). If array-like, the array values are used as the contour levels. The values should be in µV for EEG, fT for magnetometers and fT/m for gradiometers. If colorbar=True, the colorbar will have ticks corresponding to the contour levels. Default is 6.

outlines‘head’ | dict | None

The outlines to be drawn. If ‘head’, the default head scheme will be drawn. If dict, each key refers to a tuple of x and y positions, the values in ‘mask_pos’ will serve as image mask. Alternatively, a matplotlib patch object can be passed for advanced masking options, either directly or as a function that returns patches (required for multi-axis plots). If None, nothing will be drawn. Defaults to ‘head’.

spherefloat | array_like | instance of ConductorModel | None | ‘auto’ | ‘eeglab’

The sphere parameters to use for the head outline. Can be array-like of shape (4,) to give the X/Y/Z origin and radius in meters, or a single float to give just the radius (origin assumed 0, 0, 0). Can also be an instance of a spherical ConductorModel to use the origin and radius from that object. If 'auto' the sphere is fit to digitization points. If 'eeglab' the head circle is defined by EEG electrodes 'Fpz', 'Oz', 'T7', and 'T8' (if 'Fpz' is not present, it will be approximated from the coordinates of 'Oz'). None (the default) is equivalent to 'auto' when enough extra digitization points are available, and (0, 0, 0, 0.095) otherwise.

New in version 0.20.

Changed in version 1.1: Added 'eeglab' option.

image_interpstr

The image interpolation to be used. Options are 'cubic' (default) to use scipy.interpolate.CloughTocher2DInterpolator, 'nearest' to use scipy.spatial.Voronoi or 'linear' to use scipy.interpolate.LinearNDInterpolator.

extrapolatestr

Options:

  • 'box'

    Extrapolate to four points placed to form a square encompassing all data points, where each side of the square is three times the range of the data in the respective dimension.

  • 'local' (default for MEG sensors)

    Extrapolate only to nearby points (approximately to points closer than median inter-electrode distance). This will also set the mask to be polygonal based on the convex hull of the sensors.

  • 'head' (default for non-MEG sensors)

    Extrapolate out to the edges of the clipping circle. This will be on the head circle when the sensors are contained within the head circle, but it can extend beyond the head when sensors are plotted outside the head circle.

Changed in version 0.21:

  • The default was changed to 'local' for MEG sensors.

  • 'local' was changed to use a convex hull mask

  • 'head' was changed to extrapolate out to the clipping circle.

borderfloat | ‘mean’

Value to extrapolate to on the topomap borders. If 'mean' (default), then each extrapolated point has the average value of its neighbours.

New in version 0.20.

resint

The resolution of the topomap image (number of pixels along each side).

sizefloat

Side length of each subplot in inches.

cmapmatplotlib colormap | (colormap, bool) | ‘interactive’ | None

Colormap to use. If tuple, the first value indicates the colormap to use and the second value is a boolean defining interactivity. In interactive mode the colors are adjustable by clicking and dragging the colorbar with left and right mouse button. Left mouse button moves the scale up and down and right mouse button adjusts the range. Hitting space bar resets the range. Up and down arrows can be used to change the colormap. If None, 'Reds' is used for data that is either all-positive or all-negative, and 'RdBu_r' is used otherwise. 'interactive' is equivalent to (None, True). Defaults to None.

Warning

Interactive mode works smoothly only for a small amount of topomaps. Interactive mode is disabled by default for more than 2 topomaps.

vlimtuple of length 2 | ‘joint’

Colormap limits to use. If a tuple of floats, specifies the lower and upper bounds of the colormap (in that order); providing None for either entry will set the corresponding boundary at the min/max of the data (separately for each topomap). Elements of the tuple may also be callable functions which take in a NumPy array and return a scalar. If vlim='joint', will compute the colormap limits jointly across all topomaps of the same channel type, using the min/max of the data for that channel type. Defaults to (None, None).

cnormmatplotlib.colors.Normalize | None

How to normalize the colormap. If None, standard linear normalization is performed. If not None, vmin and vmax will be ignored. See Matplotlib docs for more details on colormap normalization, and the ERDs example for an example of its use.

colorbarbool

Plot a colorbar in the rightmost column of the figure.

cbar_fmtstr

Formatting string for colorbar tick labels. See Format Specification Mini-Language for details. If 'auto', is equivalent to ‘%0.3f’ if dB=False and ‘%0.1f’ if dB=True. Defaults to 'auto'.

unitsstr | None

The units to use for the colorbar label. Ignored if colorbar=False. If None the label will be “AU” indicating arbitrary units. Default is None.

axesinstance of Axes | list of Axes | None

The axes to plot to. If None, a new Figure will be created with the correct number of axes. If Axes are provided (either as a single instance or a list of axes), the number of axes provided must match the length of bands.Default is None.

showbool

Show the figure if True.

Returns:
figinstance of Figure

Figure showing one scalp topography per frequency band.

Examples using plot_topomap:

Visualizing epoched data

Visualizing epoched data
reorder_channels(ch_names)[source]#

Reorder channels.

Parameters:
ch_nameslist

The desired channel order.

Returns:
instinstance of Raw, Epochs, or Evoked

The modified instance.

Notes

Channel names must be unique. Channels that are not in ch_names are dropped.

New in version 0.16.0.

save(fname, *, overwrite=False, verbose=None)[source]#

Save spectrum data to disk (in HDF5 format).

Parameters:
fnamepath-like

Path of file to save to.

overwritebool

If True (default False), overwrite the destination file if it exists.

verbosebool | str | int | None

Control verbosity of the logging output. If None, use the default verbosity level. See the logging documentation and mne.verbose() for details. Should only be passed as a keyword argument.

to_data_frame(picks=None, index=None, copy=True, long_format=False, *, verbose=None)[source]#

Export data in tabular structure as a pandas DataFrame.

Channels are converted to columns in the DataFrame. By default, an additional column “frequency” is added, unless index='freq' (in which case frequency values form the DataFrame’s index).

Parameters:
picksstr | array_like | slice | None

Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g., ['meg', 'eeg']) will pick channels of those types, channel name strings (e.g., ['MEG0111', 'MEG2623'] will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick all channels. Note that channels in info['bads'] will be included if their names or indices are explicitly provided.

indexstr | list of str | None

Kind of index to use for the DataFrame. If None, a sequential integer index (pandas.RangeIndex) will be used. If a str, a pandas.Index will be used (see Notes). If a list of two or more string values, a pandas.MultiIndex will be used. Defaults to None.

copybool

If True, data will be copied. Otherwise data may be modified in place. Defaults to True.

long_formatbool

If True, the DataFrame is returned in long format where each row is one observation of the signal at a unique combination of frequency and channel. For convenience, a ch_type column is added to facilitate subsetting the resulting DataFrame. Defaults to False.

verbosebool | str | int | None

Control verbosity of the logging output. If None, use the default verbosity level. See the logging documentation and mne.verbose() for details. Should only be passed as a keyword argument.

Returns:
dfinstance of pandas.DataFrame

A dataframe suitable for usage with other statistical/plotting/analysis packages.

Notes

Valid values for index depend on whether the Spectrum was created from continuous data (Raw, Evoked) or discontinuous data (Epochs). For continuous data, only None or 'freq' is supported. For discontinuous data, additional valid values are 'epoch' and 'condition', or a list comprising some of the valid string values (e.g., ['freq', 'epoch']).

units(latex=False)[source]#

Get the spectrum units for each channel type.

Parameters:
latexbool

Whether to format the unit strings as LaTeX. Default is False.

Returns:
unitsdict

Mapping from channel type to a string representation of the units for that channel type.

Examples using mne.time_frequency.EpochsSpectrum#

Visualizing epoched data

Visualizing epoched data

The Spectrum and EpochsSpectrum classes: frequency-domain data

The Spectrum and EpochsSpectrum classes: frequency-domain data

Frequency and time-frequency sensor analysis

Frequency and time-frequency sensor analysis

Frequency-tagging: Basic analysis of an SSVEP/vSSR dataset

Frequency-tagging: Basic analysis of an SSVEP/vSSR dataset

Sleep stage classification from polysomnography (PSG) data

Sleep stage classification from polysomnography (PSG) data