mne.time_frequency.EpochsSpectrumArray#

class mne.time_frequency.EpochsSpectrumArray(data, info, freqs, events=None, event_id=None, dim_names=('epoch', 'channel', 'freq'), weights=None, *, verbose=None)[source]#

Data object for precomputed epoched spectral data (in NumPy array format).

Parameters:
datandarray, shape (n_epochs, n_channels, [n_tapers], n_freqs, [n_segments])

The spectra for each channel in each epoch.

infomne.Info

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

freqsndarray, shape (n_freqs,)

The frequencies in Hz.

eventsndarray of int, shape (n_events, 3)

The identity and timing of experimental events, around which the epochs were created. See events for more information.Events that don’t match the events of interest as specified by event_id will be marked as IGNORED in the drop log.

event_idint | list of int | dict | str | list of str | None

The id of the events to consider. If dict, the keys can later be used to access associated events. Example: dict(auditory=1, visual=3). If int, a dict will be created with the id as string. If a list of int, all events with the IDs specified in the list are used. If a str or list of str, events must be None to use annotations and then the IDs must be the name(s) of the annotations to use. If None, all events will be used and a dict is created with string integer names corresponding to the event id integers.

dim_namestuple of str

The name of the dimensions in the data, in the order they occur. Must contain 'channel' and 'freq'; if data are unaggregated estimates, also include either a 'segment' (e.g., Welch-like algorithms) or 'taper' (e.g., multitaper algorithms) dimension. If including 'taper', you should also pass a weights parameter.

New in v1.8.

weightsndarray | None

Weights for the 'taper' dimension, if present (see dim_names).

New in v1.8.

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.

Attributes:
ch_names
compensation_grade

The current gradient compensation grade.

data
freqs
metadata

Get the metadata.

method
nave
sfreq
shape
weights

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_types([meg, eeg, stim, eog, ecg, emg, ...])

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.

Notes

If the data passed in is real-valued, it is assumed to represent spectral power (not amplitude, phase, etc), and downstream methods (such as plot()) assume power data. If you pass in real-valued data that is not power, axis labels will be incorrect.

If the data passed in is complex-valued, it is assumed to represent Fourier coefficients. Downstream plotting methods will treat the data as such, attempting to convert this to power before visualisation. If you pass in complex-valued data that is not Fourier coefficients, axis labels will be incorrect.

New in v1.6.

__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 v0.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.

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 v0.23.0.

Returns:
instinstance of Raw, Epochs, or Evoked

The modified instance.

Notes

New in v0.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 include 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.

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 v0.24.0.

Returns:
instinstance of Raw, Epochs, or Evoked

The modified instance.

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

Warning

LEGACY: New code should use inst.pick(…).

Pick some channels.

Parameters:
ch_nameslist

The list of channels to select.

orderedbool

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

New in v0.20.0.

Changed in version 1.7: The default changed from False in 1.6 to True in 1.7.

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 v1.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 v0.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, eyetrack=False, include=(), exclude='bads', selection=None, verbose=None)[source]#

Warning

LEGACY: New code should use inst.pick(…).

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.

eyetrackbool | str

Eyetracking channels. If True include all eyetracking channels. If False (default) include none. If string it can be ‘eyegaze’ (to include eye position channels) or ‘pupil’ (to include pupil-size 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 v0.9.0.

plot(*, picks=None, average=False, dB=True, amplitude=False, xscale='linear', ci='sd', ci_alpha=0.3, color='black', alpha=None, spatial_colors=True, sphere=None, exclude=(), 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 all data channels (excluding reference MEG channels). Note that channels in info['bads'] will be included if their names or indices are explicitly provided.

Changed in version 1.5: In version 1.5, the default behavior changed so that all data channels (not just “good” data channels) are shown by default.

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

Whether to plot an amplitude spectrum (True) or power spectrum (False).

Changed in version 1.8: In version 1.8, the default changed to amplitude=False.

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 v0.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 include all channels (including “bad” channels, if any).

Changed in version 1.5: In version 1.5, the default behavior changed from exclude='bads' to exclude=().

axesinstance of Axes | list of Axes | None

The axes to plot into. 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.

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 (if possible).

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 into. 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 v0.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.

borderfloat | ‘mean’

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

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”

Lower and upper bounds of the colormap, typically a numeric value in the same units as the data. Elements of the tuple may also be callable functions which take in a NumPy array and return a scalar.

If both entries are None, the bounds are set at ± the maximum absolute value of the data (yielding a colormap with midpoint at 0), or (0, max(abs(data))) if the (possibly baselined) data are all-positive. Providing None for just one entry will set the corresponding boundary at the min/max of the data. If vlim="joint", will compute the colormap limits jointly across all topomaps of the same channel type (instead of separately for each topomap), 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 into. 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.

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 v0.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 “freq” 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.EpochsSpectrumArray#

Creating MNE-Python data structures from scratch

Creating MNE-Python data structures from scratch