mne.Evoked#

class mne.Evoked(fname, condition=None, proj=True, kind='average', allow_maxshield=False, *, verbose=None)[source]#

Evoked data.

Parameters:
fnamepath-like

Name of evoked/average FIF file to load. If None no data is loaded.

conditionint, or str

Dataset ID number (int) or comment/name (str). Optional if there is only one data set in file.

projbool, optional

Apply SSP projection vectors.

kindstr

Either 'average' or 'standard_error'. The type of data to read. Only used if ‘condition’ is a str.

allow_maxshieldbool | str (default False)

If True, allow loading of data that has been recorded with internal active compensation (MaxShield). Data recorded with MaxShield should generally not be loaded directly, but should first be processed using SSS/tSSS to remove the compensation signals that may also affect brain activity. Can also be "yes" to load without eliciting a warning.

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:
infomne.Info

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

ch_nameslist of str

Channel names.

naveint

Number of averaged epochs.

kindstr

The data kind.

commentstr

Comment on dataset. Can be the condition.

dataarray of shape (n_channels, n_times)

The data matrix.

firstint

First time sample.

lastint

Last time sample.

tminfloat

First time point.

tmaxfloat

Last time point.

timesarray

Time vector in seconds.

baselineNone | tuple of length 2

This attribute reflects whether the data has been baseline-corrected (it will be a tuple then) or not (it will be None).

Methods

__contains__(ch_type)

Check channel type membership.

__neg__()

Negate channel responses.

add_channels(add_list[, force_update_info])

Append new channels to the instance.

add_proj(projs[, remove_existing, verbose])

Add SSP projection vectors.

add_reference_channels(ref_channels)

Add reference channels to data that consists of all zeros.

animate_topomap([ch_type, times, ...])

Make animation of evoked data as topomap timeseries.

anonymize([daysback, keep_his, verbose])

Anonymize measurement information in place.

apply_baseline([baseline, verbose])

Baseline correct evoked data.

apply_function(fun[, picks, dtype, n_jobs, ...])

Apply a function to a subset of channels.

apply_hilbert([picks, envelope, n_jobs, ...])

Compute analytic signal or envelope for a subset of channels/vertices.

apply_proj([verbose])

Apply the signal space projection (SSP) operators to the data.

as_type([ch_type, mode])

Compute virtual evoked using interpolated fields.

compute_psd([method, fmin, fmax, tmin, ...])

Perform spectral analysis on sensor data.

compute_tfr(method, freqs, *[, tmin, tmax, ...])

Compute a time-frequency representation of evoked data.

copy()

Copy the instance of evoked.

crop([tmin, tmax, include_tmax, verbose])

Crop data to a given time interval.

decimate(decim[, offset, verbose])

Decimate the time-series data.

del_proj([idx])

Remove SSP projection vector.

detrend([order, picks])

Detrend data.

drop_channels(ch_names[, on_missing])

Drop channel(s).

export(fname[, fmt, overwrite, verbose])

Export Evoked to external formats.

filter(l_freq, h_freq[, picks, ...])

Filter a subset of channels/vertices.

get_channel_types([picks, unique, only_data_chs])

Get a list of channel type for each channel.

get_data([picks, units, tmin, tmax])

Get evoked data as 2D array.

get_montage()

Get a DigMontage from instance.

get_peak([ch_type, tmin, tmax, mode, ...])

Get location and latency of peak amplitude.

interpolate_bads([reset_bads, mode, origin, ...])

Interpolate bad MEG and EEG channels.

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, exclude, unit, show, ylim, ...])

Plot evoked data using butterfly plots.

plot_field(surf_maps[, time, time_label, ...])

Plot MEG/EEG fields on head surface and helmet in 3D.

plot_image([picks, exclude, unit, show, ...])

Plot evoked data as images.

plot_joint([times, title, picks, exclude, ...])

Plot evoked data as butterfly plot and add topomaps for time points.

plot_projs_topomap([ch_type, sensors, ...])

Plot SSP vector.

plot_psd([fmin, fmax, tmin, tmax, picks, ...])

Plot power or amplitude spectra.

plot_psd_topo([tmin, tmax, fmin, fmax, ...])

plot_psd_topomap([bands, tmin, tmax, ...])

plot_sensors([kind, ch_type, title, ...])

Plot sensor positions.

plot_topo([layout, layout_scale, color, ...])

Plot 2D topography of evoked responses.

plot_topomap([times, average, ch_type, ...])

Plot topographic maps of specific time points of evoked data.

plot_white(noise_cov[, show, rank, ...])

Plot whitened evoked response.

rename_channels(mapping[, allow_duplicates, ...])

Rename channels.

reorder_channels(ch_names)

Reorder channels.

resample(sfreq, *[, npad, window, n_jobs, ...])

Resample data.

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

Save evoked data to a file.

savgol_filter(h_freq[, verbose])

Filter the data using Savitzky-Golay polynomial method.

set_channel_types(mapping, *[, ...])

Specify the sensor types of channels.

set_eeg_reference([ref_channels, ...])

Specify which reference to use for EEG data.

set_meas_date(meas_date)

Set the measurement start date.

set_montage(montage[, match_case, ...])

Set EEG/sEEG/ECoG/DBS/fNIRS channel positions and digitization points.

shift_time(tshift[, relative])

Shift time scale in epoched or evoked data.

time_as_index(times[, use_rounding])

Convert time to indices.

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

Export data in tabular structure as a pandas DataFrame.

Notes

Evoked objects can only contain the average of a single set of conditions.

__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
__neg__()[source]#

Negate channel responses.

Returns:
evoked_neginstance of Evoked

The Evoked instance with channel data negated and ‘-’ prepended to the comment.

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_proj(projs, remove_existing=False, verbose=None)[source]#

Add SSP projection vectors.

Parameters:
projslist

List with projection vectors.

remove_existingbool

Remove the projection vectors currently in the file.

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:
selfinstance of Raw | Epochs | Evoked

The data container.

Examples using add_proj:

Brainstorm raw (median nerve) dataset

Brainstorm raw (median nerve) dataset
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.

animate_topomap(ch_type=None, times=None, frame_rate=None, butterfly=False, blit=True, show=True, time_unit='s', sphere=None, *, image_interp='cubic', extrapolate='auto', vmin=None, vmax=None, verbose=None)[source]#

Make animation of evoked data as topomap timeseries.

The animation can be paused/resumed with left mouse button. Left and right arrow keys can be used to move backward or forward in time.

Parameters:
ch_typestr | None

Channel type to plot. Accepted data types: ‘mag’, ‘grad’, ‘eeg’, ‘hbo’, ‘hbr’, ‘fnirs_cw_amplitude’, ‘fnirs_fd_ac_amplitude’, ‘fnirs_fd_phase’, and ‘fnirs_od’. If None, first available channel type from the above list is used. Defaults to None.

timesarray of float | None

The time points to plot. If None, 10 evenly spaced samples are calculated over the evoked time series. Defaults to None.

frame_rateint | None

Frame rate for the animation in Hz. If None, frame rate = sfreq / 10. Defaults to None.

butterflybool

Whether to plot the data as butterfly plot under the topomap. Defaults to False.

blitbool

Whether to use blit to optimize drawing. In general, it is recommended to use blit in combination with show=True. If you intend to save the animation it is better to disable blit. Defaults to True.

showbool

Whether to show the animation. Defaults to True.

time_unitstr

The units for the time axis, can be “ms” (default in 0.16) or “s” (will become the default in 0.17).

New in v0.16.

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.

New in v0.22.

vmin, vmaxfloat | callable() | None

Lower and upper bounds of the colormap, in the same units as the data. If vmin and vmax are both None, the bounds are set at ± the maximum absolute value of the data (yielding a colormap with midpoint at 0). If only one of vmin, vmax is None, will use min(data) or max(data), respectively. If callable, should accept a NumPy array of data and return a float.

New in v1.1.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.

Returns:
figinstance of matplotlib.figure.Figure

The figure.

animinstance of matplotlib.animation.FuncAnimation

Animation of the topomap.

Notes

New in v0.12.0.

Examples using animate_topomap:

Plotting topographic maps of evoked data

Plotting topographic maps of evoked data
anonymize(daysback=None, keep_his=False, verbose=None)[source]#

Anonymize measurement information in place.

Parameters:
daysbackint | None

Number of days to subtract from all dates. If None (default), the acquisition date, info['meas_date'], will be set to January 1ˢᵗ, 2000. This parameter is ignored if info['meas_date'] is None (i.e., no acquisition date has been set).

keep_hisbool

If True, his_id of subject_info will not be overwritten. Defaults to False.

Warning

This could mean that info is not fully anonymized. Use with caution.

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 | Evoked

The modified instance.

Notes

Removes potentially identifying information if it exists in info. Specifically for each of the following we use:

  • meas_date, file_id, meas_id

    A default value, or as specified by daysback.

  • subject_info

    Default values, except for ‘birthday’ which is adjusted to maintain the subject age.

  • experimenter, proj_name, description

    Default strings.

  • utc_offset

    None.

  • proj_id

    Zeros.

  • proc_history

    Dates use the meas_date logic, and experimenter a default string.

  • helium_info, device_info

    Dates use the meas_date logic, meta info uses defaults.

If info['meas_date'] is None, it will remain None during processing the above fields.

Operates in place.

New in v0.13.0.

apply_baseline(baseline=(None, 0), *, verbose=None)[source]#

Baseline correct evoked data.

Parameters:
baselineNone | tuple of length 2

The time interval to consider as “baseline” when applying baseline correction. If None, do not apply baseline correction. If a tuple (a, b), the interval is between a and b (in seconds), including the endpoints. If a is None, the beginning of the data is used; and if b is None, it is set to the end of the data. If (None, None), the entire time interval is used.

Note

The baseline (a, b) includes both endpoints, i.e. all timepoints t such that a <= t <= b.

Correction is applied to each channel individually in the following way:

  1. Calculate the mean signal of the baseline period.

  2. Subtract this mean from the entire Evoked.

Defaults to (None, 0), i.e. beginning of the the data until time point zero.

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:
evokedinstance of Evoked

The baseline-corrected Evoked object.

Notes

Baseline correction can be done multiple times.

New in v0.13.0.

Examples using apply_baseline:

Getting started with mne.Report

Getting started with mne.Report

Repairing artifacts with regression

Repairing artifacts with regression

Repairing artifacts with ICA

Repairing artifacts with ICA

Repairing artifacts with SSP

Repairing artifacts with SSP

Using the event system to link figures

Using the event system to link figures
apply_function(fun, picks=None, dtype=None, n_jobs=None, channel_wise=True, *, verbose=None, **kwargs)[source]#

Apply a function to a subset of channels.

The function fun is applied to the channels defined in picks. The evoked object’s data is modified in-place. If the function returns a different data type (e.g. numpy.complex128) it must be specified using the dtype parameter, which causes the data type of all the data to change (even if the function is only applied to channels in picks).

Note

If n_jobs > 1, more memory is required as len(picks) * n_times additional time points need to be temporarily stored in memory.

Note

If the data type changes (dtype != None), more memory is required since the original and the converted data needs to be stored in memory.

Parameters:
funcallable()

A function to be applied to the channels. The first argument of fun has to be a timeseries (numpy.ndarray). The function must operate on an array of shape (n_times,) because it will apply channel-wise. The function must return an ndarray shaped like its input.

Note

If channel_wise=True, one can optionally access the index and/or the name of the currently processed channel within the applied function. This can enable tailored computations for different channels. To use this feature, add ch_idx and/or ch_name as additional argument(s) to your function definition.

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.

dtypenumpy.dtype

Data type to use after applying the function. If None (default) the data type is not modified.

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_config context manager that sets another value for n_jobs. Ignored if channel_wise=False as the workload is split across channels.

channel_wisebool

Whether to apply the function to each channel individually. If False, the function will be applied to all channels at once. Default True.

New in v1.6.

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.

**kwargsdict

Additional keyword arguments to pass to fun.

Returns:
selfinstance of Evoked

The evoked object with transformed data.

apply_hilbert(picks=None, envelope=False, n_jobs=None, n_fft='auto', *, verbose=None)[source]#

Compute analytic signal or envelope for a subset of channels/vertices.

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.

envelopebool

Compute the envelope signal of each channel/vertex. Default False. See Notes.

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_config context manager that sets another value for n_jobs.

n_fftint | None | str

Points to use in the FFT for Hilbert transformation. The signal will be padded with zeros before computing Hilbert, then cut back to original length. If None, n == self.n_times. If ‘auto’, the next highest fast FFT length will be use.

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:
selfinstance of Raw, Epochs, Evoked or SourceEstimate

The raw object with transformed data.

Notes

Parameters

If envelope=False, the analytic signal for the channels/vertices defined in picks is computed and the data of the Raw object is converted to a complex representation (the analytic signal is complex valued).

If envelope=True, the absolute value of the analytic signal for the channels/vertices defined in picks is computed, resulting in the envelope signal.

If envelope=False, more memory is required since the original raw data as well as the analytic signal have temporarily to be stored in memory. If n_jobs > 1, more memory is required as len(picks) * n_times additional time points need to be temporarily stored in memory.

Also note that the n_fft parameter will allow you to pad the signal with zeros before performing the Hilbert transform. This padding is cut off, but it may result in a slightly different result (particularly around the edges). Use at your own risk.

Analytic signal

The analytic signal “x_a(t)” of “x(t)” is:

x_a = F^{-1}(F(x) 2U) = x + i y

where “F” is the Fourier transform, “U” the unit step function, and “y” the Hilbert transform of “x”. One usage of the analytic signal is the computation of the envelope signal, which is given by “e(t) = abs(x_a(t))”. Due to the linearity of Hilbert transform and the MNE inverse solution, the enevlope in source space can be obtained by computing the analytic signal in sensor space, applying the MNE inverse, and computing the envelope in source space.

apply_proj(verbose=None)[source]#

Apply the signal space projection (SSP) operators to the data.

Parameters:
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:
selfinstance of Raw | Epochs | Evoked

The instance.

Notes

Once the projectors have been applied, they can no longer be removed. It is usually not recommended to apply the projectors at too early stages, as they are applied automatically later on (e.g. when computing inverse solutions). Hint: using the copy method individual projection vectors can be tested without affecting the original data. With evoked data, consider the following example:

projs_a = mne.read_proj('proj_a.fif')
projs_b = mne.read_proj('proj_b.fif')
# add the first, copy, apply and see ...
evoked.add_proj(a).copy().apply_proj().plot()
# add the second, copy, apply and see ...
evoked.add_proj(b).copy().apply_proj().plot()
# drop the first and see again
evoked.copy().del_proj(0).apply_proj().plot()
evoked.apply_proj()  # finally keep both

Examples using apply_proj:

Brainstorm raw (median nerve) dataset

Brainstorm raw (median nerve) dataset
as_type(ch_type='grad', mode='fast')[source]#

Compute virtual evoked using interpolated fields.

Warning

Using virtual evoked to compute inverse can yield unexpected results. The virtual channels have '_v' appended at the end of the names to emphasize that the data contained in them are interpolated.

Parameters:
ch_typestr

The destination channel type. It can be ‘mag’ or ‘grad’.

modestr

Either 'accurate' or 'fast', determines the quality of the Legendre polynomial expansion used. 'fast' should be sufficient for most applications.

Returns:
evokedinstance of mne.Evoked

The transformed evoked object containing only virtual channels.

Notes

This method returns a copy and does not modify the data it operates on. It also returns an EvokedArray instance.

New in v0.9.0.

Examples using as_type:

Remap MEG channel types

Remap MEG channel types
property ch_names#

Channel names.

property compensation_grade#

The current gradient compensation grade.

compute_psd(method='multitaper', fmin=0, fmax=inf, tmin=None, tmax=None, picks=None, proj=False, remove_dc=True, exclude=(), *, n_jobs=1, verbose=None, **method_kw)[source]#

Perform spectral analysis on sensor data.

Parameters:
method'welch' | 'multitaper'

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

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.

remove_dcbool

If True, the mean is subtracted from each segment before computing its spectrum.

excludelist of str | ‘bads’

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

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_config 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. Note that for Welch method if n_fft is unspecified its default will be the smaller of 2048 or the number of available time samples (taking into account tmin and tmax), not 256 as in psd_array_welch().

Returns:
spectruminstance of Spectrum

The spectral representation of the data.

Notes

New in v1.2.

References

Examples using compute_psd:

The Spectrum and EpochsSpectrum classes: frequency-domain data

The Spectrum and EpochsSpectrum classes: frequency-domain data
compute_tfr(method, freqs, *, tmin=None, tmax=None, picks=None, proj=False, output='power', decim=1, n_jobs=None, verbose=None, **method_kw)[source]#

Compute a time-frequency representation of evoked data.

Parameters:
method'morlet' | 'multitaper' | None

Spectrotemporal power estimation method. 'morlet' uses Morlet wavelets, 'multitaper' uses DPSS tapers [2]. None (the default) only works when using __setstate__ and will raise an error otherwise.

freqsarray_like | None

The frequencies at which to compute the power estimates. Must be an array of shape (n_freqs,). None (the default) only works when using __setstate__ and will raise an error otherwise.

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.

outputstr

What kind of estimate to return. Allowed values are "complex", "phase", and "power". Default is "power".

decimint | slice

Decimation factor, applied after time-frequency decomposition.

  • if int, returns tfr[..., ::decim] (keep only every Nth sample along the time axis).

  • if slice, returns tfr[..., decim] (keep only the specified slice along the time axis).

Note

Decimation is done after convolutions and may create aliasing artifacts.

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_config 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 spectrotemporal estimation function (e.g., n_cycles, use_fft, zero_mean for Morlet method or n_cycles, use_fft, zero_mean, time_bandwidth for multitaper method). See tfr_array_morlet() and tfr_array_multitaper() for additional details.

Returns:
tfrinstance of AverageTFR

The time-frequency-resolved power estimates of the data.

Notes

New in v1.7.

References

copy()[source]#

Copy the instance of evoked.

Returns:
evokedinstance of Evoked

A copy of the object.

Examples using copy:

Preprocessing optically pumped magnetometer (OPM) MEG data

Preprocessing optically pumped magnetometer (OPM) MEG data

Auto-generating Epochs metadata

Auto-generating Epochs metadata

The Evoked data structure: evoked/averaged data

The Evoked data structure: evoked/averaged data

EEG analysis - Event-Related Potentials (ERPs)

EEG analysis - Event-Related Potentials (ERPs)

Computing a covariance matrix

Computing a covariance matrix

Source localization with equivalent current dipole (ECD) fit

Source localization with equivalent current dipole (ECD) fit

4D Neuroimaging/BTi phantom dataset tutorial

4D Neuroimaging/BTi phantom dataset tutorial

Working with ECoG data

Working with ECoG data

Interpolate bad channels for MEG/EEG channels

Interpolate bad channels for MEG/EEG channels

Plotting topographic arrowmaps of evoked data

Plotting topographic arrowmaps of evoked data

Compute source power spectral density (PSD) of VectorView and OPM data

Compute source power spectral density (PSD) of VectorView and OPM data

Computing source timecourses with an XFit-like multi-dipole model

Computing source timecourses with an XFit-like multi-dipole model

Compute iterative reweighted TF-MxNE with multiscale time-frequency dictionary

Compute iterative reweighted TF-MxNE with multiscale time-frequency dictionary

Computing source space SNR

Computing source space SNR

Brainstorm raw (median nerve) dataset

Brainstorm raw (median nerve) dataset

HF-SEF dataset

HF-SEF dataset

Optically pumped magnetometer (OPM) data

Optically pumped magnetometer (OPM) data
crop(tmin=None, tmax=None, include_tmax=True, verbose=None)[source]#

Crop data to a given time interval.

Parameters:
tminfloat | None

Start time of selection in seconds.

tmaxfloat | None

End time of selection in seconds.

include_tmaxbool

If True (default), include tmax. If False, exclude tmax (similar to how Python indexing typically works).

New in v0.19.

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, Evoked, AverageTFR, or SourceEstimate

The cropped time-series object, modified in-place.

Notes

Unlike Python slices, MNE time intervals by default include both their end points; crop(tmin, tmax) returns the interval tmin <= t <= tmax. Pass include_tmax=False to specify the half-open interval tmin <= t < tmax instead.

Examples using crop:

Source localization with equivalent current dipole (ECD) fit

Source localization with equivalent current dipole (ECD) fit

Computing various MNE solutions

Computing various MNE solutions

Visualize source time courses (stcs)

Visualize source time courses (stcs)

Brainstorm CTF phantom dataset tutorial

Brainstorm CTF phantom dataset tutorial

Non-parametric 1 sample cluster statistic on single trial power

Non-parametric 1 sample cluster statistic on single trial power

Source localization with a custom inverse solver

Source localization with a custom inverse solver

Compute a sparse inverse solution using the Gamma-MAP empirical Bayesian method

Compute a sparse inverse solution using the Gamma-MAP empirical Bayesian method

Compute sparse inverse solution with mixed norm: MxNE and irMxNE

Compute sparse inverse solution with mixed norm: MxNE and irMxNE

Compute iterative reweighted TF-MxNE with multiscale time-frequency dictionary

Compute iterative reweighted TF-MxNE with multiscale time-frequency dictionary

Compute Rap-Music on evoked data

Compute Rap-Music on evoked data

Compute MxNE with time-frequency sparse prior

Compute MxNE with time-frequency sparse prior

Compute Trap-Music on evoked data

Compute Trap-Music on evoked data
property data#

The data matrix.

decimate(decim, offset=0, *, verbose=None)[source]#

Decimate the time-series data.

Parameters:
decimint

Factor by which to subsample the data.

Warning

Low-pass filtering is not performed, this simply selects every Nth sample (where N is the value passed to decim), i.e., it compresses the signal (see Notes). If the data are not properly filtered, aliasing artifacts may occur. See Resampling and decimating data for more information.

offsetint

Apply an offset to where the decimation starts relative to the sample corresponding to t=0. The offset is in samples at the current sampling rate.

New in v0.12.

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:
instMNE-object

The decimated object.

Notes

For historical reasons, decim / “decimation” refers to simply subselecting samples from a given signal. This contrasts with the broader signal processing literature, where decimation is defined as (quoting [3], p. 172; which cites [4]):

“… a general system for downsampling by a factor of M is the one shown in Figure 4.23. Such a system is called a decimator, and downsampling by lowpass filtering followed by compression [i.e, subselecting samples] has been termed decimation (Crochiere and Rabiner, 1983).”

Hence “decimation” in MNE is what is considered “compression” in the signal processing community.

Decimation can be done multiple times. For example, inst.decimate(2).decimate(2) will be the same as inst.decimate(4).

If decim is 1, this method does not copy the underlying data.

New in v0.10.0.

References

Examples using decimate:

Visualize source time courses (stcs)

Visualize source time courses (stcs)
del_proj(idx='all')[source]#

Remove SSP projection vector.

Note

The projection vector can only be removed if it is inactive (has not been applied to the data).

Parameters:
idxint | list of int | str

Index of the projector to remove. Can also be “all” (default) to remove all projectors.

Returns:
selfinstance of Raw | Epochs | Evoked

The instance.

Examples using del_proj:

Repairing artifacts with SSP

Repairing artifacts with SSP
detrend(order=1, picks=None)[source]#

Detrend data.

This function operates in-place.

Parameters:
orderint

Either 0 or 1, the order of the detrending. 0 is a constant (DC) detrend, 1 is a linear detrend.

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. Note that channels in info['bads'] will be included if their names or indices are explicitly provided.

Returns:
evokedinstance of Evoked

The detrended evoked 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.

Examples using drop_channels:

Compute source power estimate by projecting the covariance with MNE

Compute source power estimate by projecting the covariance with MNE
export(fname, fmt='auto', *, overwrite=False, verbose=None)[source]#

Export Evoked to external formats.

Supported formats:

Warning

Since we are exporting to external formats, there’s no guarantee that all the info will be preserved in the external format. See Notes for details.

Parameters:
fnamestr

Name of the output file.

fmt‘auto’ | ‘mff’

Format of the export. Defaults to 'auto', which will infer the format from the filename extension. See supported formats above for more information.

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.

Notes

New in v1.1.

Export to external format may not preserve all the information from the instance. To save in native MNE format (.fif) without information loss, use mne.Evoked.save() instead. Export does not apply projector(s). Unapplied projector(s) will be lost. Consider applying projector(s) before exporting with mne.Evoked.apply_proj().

filter(l_freq, h_freq, picks=None, filter_length='auto', l_trans_bandwidth='auto', h_trans_bandwidth='auto', n_jobs=None, method='fir', iir_params=None, phase='zero', fir_window='hamming', fir_design='firwin', skip_by_annotation=('edge', 'bad_acq_skip'), pad='edge', *, verbose=None)[source]#

Filter a subset of channels/vertices.

Parameters:
l_freqfloat | None

For FIR filters, the lower pass-band edge; for IIR filters, the lower cutoff frequency. If None the data are only low-passed.

h_freqfloat | None

For FIR filters, the upper pass-band edge; for IIR filters, the upper cutoff frequency. If None the data are only high-passed.

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. Note that channels in info['bads'] will be included if their names or indices are explicitly provided.

filter_lengthstr | int

Length of the FIR filter to use (if applicable):

  • ‘auto’ (default): The filter length is chosen based on the size of the transition regions (6.6 times the reciprocal of the shortest transition band for fir_window=’hamming’ and fir_design=”firwin2”, and half that for “firwin”).

  • str: A human-readable time in units of “s” or “ms” (e.g., “10s” or “5500ms”) will be converted to that number of samples if phase="zero", or the shortest power-of-two length at least that duration for phase="zero-double".

  • int: Specified length in samples. For fir_design=”firwin”, this should not be used.

l_trans_bandwidthfloat | str

Width of the transition band at the low cut-off frequency in Hz (high pass or cutoff 1 in bandpass). Can be “auto” (default) to use a multiple of l_freq:

min(max(l_freq * 0.25, 2), l_freq)

Only used for method='fir'.

h_trans_bandwidthfloat | str

Width of the transition band at the high cut-off frequency in Hz (low pass or cutoff 2 in bandpass). Can be “auto” (default in 0.14) to use a multiple of h_freq:

min(max(h_freq * 0.25, 2.), info['sfreq'] / 2. - h_freq)

Only used for method='fir'.

n_jobsint | str

Number of jobs to run in parallel. Can be 'cuda' if cupy is installed properly and method='fir'.

methodstr

'fir' will use overlap-add FIR filtering, 'iir' will use IIR forward-backward filtering (via filtfilt()).

iir_paramsdict | None

Dictionary of parameters to use for IIR filtering. If iir_params=None and method="iir", 4th order Butterworth will be used. For more information, see mne.filter.construct_iir_filter().

phasestr

Phase of the filter. When method='fir', symmetric linear-phase FIR filters are constructed with the following behaviors when method="fir":

"zero" (default)

The delay of this filter is compensated for, making it non-causal.

"minimum"

A minimum-phase filter will be constructed by decomposing the zero-phase filter into a minimum-phase and all-pass systems, and then retaining only the minimum-phase system (of the same length as the original zero-phase filter) via scipy.signal.minimum_phase().

"zero-double"

This is a legacy option for compatibility with MNE <= 0.13. The filter is applied twice, once forward, and once backward (also making it non-causal).

"minimum-half"

This is a legacy option for compatibility with MNE <= 1.6. A minimum-phase filter will be reconstructed from the zero-phase filter with half the length of the original filter.

When method='iir', phase='zero' (default) or equivalently 'zero-double' constructs and applies IIR filter twice, once forward, and once backward (making it non-causal) using filtfilt(); phase='forward' will apply the filter once in the forward (causal) direction using lfilter().

New in v0.13.

Changed in version 1.7: The behavior for phase="minimum" was fixed to use a filter of the requested length and improved suppression.

fir_windowstr

The window to use in FIR design, can be “hamming” (default), “hann” (default in 0.13), or “blackman”.

New in v0.15.

fir_designstr

Can be “firwin” (default) to use scipy.signal.firwin(), or “firwin2” to use scipy.signal.firwin2(). “firwin” uses a time-domain design technique that generally gives improved attenuation using fewer samples than “firwin2”.

New in v0.15.

skip_by_annotationstr | list of str

If a string (or list of str), any annotation segment that begins with the given string will not be included in filtering, and segments on either side of the given excluded annotated segment will be filtered separately (i.e., as independent signals). The default (('edge', 'bad_acq_skip') will separately filter any segments that were concatenated by mne.concatenate_raws() or mne.io.Raw.append(), or separated during acquisition. To disable, provide an empty list. Only used if inst is raw.

New in v0.16..

padstr

The type of padding to use. Supports all numpy.pad() mode options. Can also be "reflect_limited", which pads with a reflected version of each vector mirrored on the first and last values of the vector, followed by zeros. Only used for method='fir'.

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 Epochs, Evoked, SourceEstimate, or Raw

The filtered data.

Notes

Applies a zero-phase low-pass, high-pass, band-pass, or band-stop filter to the channels selected by picks. The data are modified inplace.

The object has to have the data loaded e.g. with preload=True or self.load_data().

l_freq and h_freq are the frequencies below which and above which, respectively, to filter out of the data. Thus the uses are:

  • l_freq < h_freq: band-pass filter

  • l_freq > h_freq: band-stop filter

  • l_freq is not None and h_freq is None: high-pass filter

  • l_freq is None and h_freq is not None: low-pass filter

self.info['lowpass'] and self.info['highpass'] are only updated with picks=None.

Note

If n_jobs > 1, more memory is required as len(picks) * n_times additional time points need to be temporarily stored in memory.

When working on SourceEstimates the sample rate of the original data is inferred from tstep.

For more information, see the tutorials Background information on filtering and Filtering and resampling data and mne.filter.create_filter().

New in v0.15.

Examples using filter:

Working with CTF data: the Brainstorm auditory dataset

Working with CTF data: the Brainstorm auditory dataset

HF-SEF dataset

HF-SEF dataset
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, units=None, tmin=None, tmax=None)[source]#

Get evoked data as 2D array.

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.

unitsstr | dict | None

Specify the unit(s) that the data should be returned in. If None (default), the data is returned in the channel-type-specific default units, which are SI units (see Internal representation (units) and data channels). If a string, must be a sub-multiple of SI units that will be used to scale the data from all channels of the type associated with that unit. This only works if the data contains one channel type that has a unit (unitless channel types are left unchanged). For example if there are only EEG and STIM channels, units='uV' will scale EEG channels to micro-Volts while STIM channels will be unchanged. Finally, if a dictionary is provided, keys must be channel types, and values must be units to scale the data of that channel type to. For example dict(grad='fT/cm', mag='fT') will scale the corresponding types accordingly, but all other channel types will remain in their channel-type-specific default unit.

tminfloat | None

Start time of data to get in seconds.

tmaxfloat | None

End time of data to get in seconds.

Returns:
datandarray, shape (n_channels, n_times)

A view on evoked data.

Notes

New in v0.24.

Examples using get_data:

Regression-based baseline correction

Regression-based baseline correction
get_montage()[source]#

Get a DigMontage from instance.

Returns:
montageNone | str | DigMontage

A montage containing channel positions. If a string or DigMontage is specified, the existing channel information will be updated with the channel positions from the montage. Valid strings are the names of the built-in montages that ship with MNE-Python; you can list those via mne.channels.get_builtin_montages(). If None (default), the channel positions will be removed from the Info.

get_peak(ch_type=None, tmin=None, tmax=None, mode='abs', time_as_index=False, merge_grads=False, return_amplitude=False, *, strict=True)[source]#

Get location and latency of peak amplitude.

Parameters:
ch_typestr | None

The channel type to use. Defaults to None. If more than one channel type is present in the data, this value must be provided.

tminfloat | None

The minimum point in time to be considered for peak getting. If None (default), the beginning of the data is used.

tmaxfloat | None

The maximum point in time to be considered for peak getting. If None (default), the end of the data is used.

mode‘pos’ | ‘neg’ | ‘abs’

How to deal with the sign of the data. If ‘pos’ only positive values will be considered. If ‘neg’ only negative values will be considered. If ‘abs’ absolute values will be considered. Defaults to ‘abs’.

time_as_indexbool

Whether to return the time index instead of the latency in seconds.

merge_gradsbool

If True, compute peak from merged gradiometer data.

return_amplitudebool

If True, return also the amplitude at the maximum response.

New in v0.16.

strictbool

If True, raise an error if values are all positive when detecting a minimum (mode=’neg’), or all negative when detecting a maximum (mode=’pos’). Defaults to True.

New in v1.7.

Returns:
ch_namestr

The channel exhibiting the maximum response.

latencyfloat | int

The time point of the maximum response, either latency in seconds or index.

amplitudefloat

The amplitude of the maximum response. Only returned if return_amplitude is True.

New in v0.16.

Examples using get_peak:

The Evoked data structure: evoked/averaged data

The Evoked data structure: evoked/averaged data

EEG analysis - Event-Related Potentials (ERPs)

EEG analysis - Event-Related Potentials (ERPs)

Make figures more publication ready

Make figures more publication ready
interpolate_bads(reset_bads=True, mode='accurate', origin='auto', method=None, exclude=(), verbose=None)[source]#

Interpolate bad MEG and EEG channels.

Operates in place.

Parameters:
reset_badsbool

If True, remove the bads from info.

modestr

Either 'accurate' or 'fast', determines the quality of the Legendre polynomial expansion used for interpolation of channels using the minimum-norm method.

originarray_like, shape (3,) | str

Origin of the sphere in the head coordinate frame and in meters. Can be 'auto' (default), which means a head-digitization-based origin fit.

New in v0.17.

methoddict | str | None

Method to use for each channel type.

  • "meg" channels support "MNE" (default) and "nan"

  • "eeg" channels support "spline" (default), "MNE" and "nan"

  • "fnirs" channels support "nearest" (default) and "nan"

  • "ecog" channels support "spline" (default) and "nan"

  • "seeg" channels support "spline" (default) and "nan"

None is an alias for:

method=dict(meg="MNE", eeg="spline", fnirs="nearest")

If a str is provided, the method will be applied to all channel types supported and available in the instance. The method "nan" will replace the channel data with np.nan.

Warning

Be careful when using method="nan"; the default value reset_bads=True may not be what you want.

New in v0.21.

excludelist | tuple

The channels to exclude from interpolation. If excluded a bad channel will stay in bads.

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.

Notes

The "MNE" method uses minimum-norm projection to a sphere and back.

New in v0.9.0.

property kind#

The data kind.

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.

Examples using pick:

Overview of MEG/EEG analysis with MNE-Python

Overview of MEG/EEG analysis with MNE-Python

Getting started with mne.Report

Getting started with mne.Report

EEG analysis - Event-Related Potentials (ERPs)

EEG analysis - Event-Related Potentials (ERPs)

Source localization with equivalent current dipole (ECD) fit

Source localization with equivalent current dipole (ECD) fit

Visualize source time courses (stcs)

Visualize source time courses (stcs)

Make figures more publication ready

Make figures more publication ready

Using the event system to link figures

Using the event system to link figures

Source localization with a custom inverse solver

Source localization with a custom inverse solver

Compute a sparse inverse solution using the Gamma-MAP empirical Bayesian method

Compute a sparse inverse solution using the Gamma-MAP empirical Bayesian method

Compute sparse inverse solution with mixed norm: MxNE and irMxNE

Compute sparse inverse solution with mixed norm: MxNE and irMxNE

Computing source timecourses with an XFit-like multi-dipole model

Computing source timecourses with an XFit-like multi-dipole model

Compute Rap-Music on evoked data

Compute Rap-Music on evoked data

Compute MxNE with time-frequency sparse prior

Compute MxNE with time-frequency sparse prior

Compute Trap-Music on evoked data

Compute Trap-Music on evoked data
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.

Examples using pick_channels:

EEG analysis - Event-Related Potentials (ERPs)

EEG analysis - Event-Related Potentials (ERPs)
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, exclude='bads', unit=True, show=True, ylim=None, xlim='tight', proj=False, hline=None, units=None, scalings=None, titles=None, axes=None, gfp=False, window_title=None, spatial_colors='auto', zorder='unsorted', selectable=True, noise_cov=None, time_unit='s', sphere=None, *, highlight=None, verbose=None)[source]#

Plot evoked data using butterfly plots.

Left click to a line shows the channel name. Selecting an area by clicking and holding left mouse button plots a topographic map of the painted area.

Note

If bad channels are not excluded they are shown in red.

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 of str | 'bads'

Channels names to exclude from being shown. If 'bads', the bad channels are excluded.

unitbool

Scale plot with channel (SI) unit.

showbool

Show figure if True.

ylimdict | None

Y-axis limits for plots (after scaling has been applied). dict keys should match channel types; valid keys are for instance eeg, mag, grad, misc, csd, .. (example: ylim=dict(eeg=[-20, 20])). If None, the y-axis limits will be set automatically by matplotlib. Defaults to None.

xlim'tight' | tuple | None

Limits for the X-axis of the plots.

projbool | ‘interactive’ | ‘reconstruct’

If true SSP projections are applied before display. If 'interactive', a check box for reversible selection of SSP projection vectors will be shown. If 'reconstruct', projection vectors will be applied and then M/EEG data will be reconstructed via field mapping to reduce the signal bias caused by projection.

Changed in version 0.21: Support for ‘reconstruct’ was added.

hlinelist of float | None

The values at which to show an horizontal line.

unitsdict | None

The units of the channel types used for axes labels. If None, defaults to dict(eeg='µV', grad='fT/cm', mag='fT').

scalingsdict | None

The scalings of the channel types to be applied for plotting. If None, defaults to dict(eeg=1e6, grad=1e13, mag=1e15).

titlesdict | None

The titles associated with the channels. If None, defaults to dict(eeg='EEG', grad='Gradiometers', mag='Magnetometers').

axesinstance of Axes | list | None

The axes to plot to. If list, the list must be a list of Axes of the same length as the number of channel types. If instance of Axes, there must be only one channel type plotted.

gfpbool | 'only'

Plot the global field power (GFP) or the root mean square (RMS) of the data. For MEG data, this will plot the RMS. For EEG, it plots GFP, i.e. the standard deviation of the signal across channels. The GFP is equivalent to the RMS of an average-referenced signal.

  • True

    Plot GFP or RMS (for EEG and MEG, respectively) and traces for all channels.

  • 'only'

    Plot GFP or RMS (for EEG and MEG, respectively), and omit the traces for individual channels.

The color of the GFP/RMS trace will be green if spatial_colors=False, and black otherwise.

Changed in version 0.23: Plot GFP for EEG instead of RMS. Label RMS traces correctly as such.

window_titlestr | None

The title to put at the top of the figure.

spatial_colorsbool | ‘auto’

If True, the lines are color coded by mapping physical sensor coordinates into color values. Spatially similar channels will have similar colors. Bad channels will be dotted. If False, the good channels are plotted black and bad channels red. If 'auto', uses True if channel locations are present, and False if channel locations are missing or if the data contains only a single channel. Defaults to 'auto'.

zorderstr | callable()

Which channels to put in the front or back. Only matters if spatial_colors is used. If str, must be std or unsorted (defaults to unsorted). If std, data with the lowest standard deviation (weakest effects) will be put in front so that they are not obscured by those with stronger effects. If unsorted, channels are z-sorted as in the evoked instance. If callable, must take one argument: a numpy array of the same dimensionality as the evoked raw data; and return a list of unique integers corresponding to the number of channels.

New in v0.13.0.

selectablebool

Whether to use interactive features. If True (default), it is possible to paint an area to draw topomaps. When False, the interactive features are disabled. Disabling interactive features reduces memory consumption and is useful when using axes parameter to draw multiaxes figures.

New in v0.13.0.

noise_covinstance of Covariance | str | None

Noise covariance used to whiten the data while plotting. Whitened data channel names are shown in italic. Can be a string to load a covariance from disk. See also mne.Evoked.plot_white() for additional inspection of noise covariance properties when whitening evoked data. For data processed with SSS, the effective dependence between magnetometers and gradiometers may introduce differences in scaling, consider using mne.Evoked.plot_white().

New in v0.16.0.

time_unitstr

The units for the time axis, can be “s” (default) or “ms”.

New in v0.16.

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.

highlightarray_like of float, shape(2,) | array_like of float, shape (n, 2) | None

Segments of the data to highlight by means of a light-yellow background color. Can be used to put visual emphasis on certain time periods. The time periods must be specified as array-like objects in the form of (t_start, t_end) in the unit given by the time_unit parameter. Multiple time periods can be specified by passing an array-like object of individual time periods (e.g., for 3 time periods, the shape of the passed object would be (3, 2). If None, no highlighting is applied.

New in v1.1.

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:
figinstance of matplotlib.figure.Figure

Figure containing the butterfly plots.

Examples using plot:

Working with CTF data: the Brainstorm auditory dataset

Working with CTF data: the Brainstorm auditory dataset

Repairing artifacts with regression

Repairing artifacts with regression

Repairing artifacts with SSP

Repairing artifacts with SSP

Preprocessing optically pumped magnetometer (OPM) MEG data

Preprocessing optically pumped magnetometer (OPM) MEG data

Regression-based baseline correction

Regression-based baseline correction

Auto-generating Epochs metadata

Auto-generating Epochs metadata

The Evoked data structure: evoked/averaged data

The Evoked data structure: evoked/averaged data

Visualizing Evoked data

Visualizing Evoked data

EEG analysis - Event-Related Potentials (ERPs)

EEG analysis - Event-Related Potentials (ERPs)

Plotting whitened data

Plotting whitened data

Source localization with MNE, dSPM, sLORETA, and eLORETA

Source localization with MNE, dSPM, sLORETA, and eLORETA

Brainstorm Elekta phantom dataset tutorial

Brainstorm Elekta phantom dataset tutorial

Brainstorm CTF phantom dataset tutorial

Brainstorm CTF phantom dataset tutorial

4D Neuroimaging/BTi phantom dataset tutorial

4D Neuroimaging/BTi phantom dataset tutorial

Non-parametric 1 sample cluster statistic on single trial power

Non-parametric 1 sample cluster statistic on single trial power

Non-parametric between conditions cluster statistic on single trial power

Non-parametric between conditions cluster statistic on single trial power

Creating MNE-Python data structures from scratch

Creating MNE-Python data structures from scratch

Make figures more publication ready

Make figures more publication ready

Generate simulated evoked data

Generate simulated evoked data

Simulate raw data using subject anatomy

Simulate raw data using subject anatomy

Generate simulated source data

Generate simulated source data

Define target events based on time lag, plot evoked response

Define target events based on time lag, plot evoked response

Reduce EOG artifacts through regression

Reduce EOG artifacts through regression

Interpolate bad channels for MEG/EEG channels

Interpolate bad channels for MEG/EEG channels

Shifting time-scale in evoked data

Shifting time-scale in evoked data

Whitening evoked data with a noise covariance

Whitening evoked data with a noise covariance

Regression on continuous data (rER[P/F])

Regression on continuous data (rER[P/F])

Analysis of evoked response using ICA and PCA reduction techniques

Analysis of evoked response using ICA and PCA reduction techniques

Compute a sparse inverse solution using the Gamma-MAP empirical Bayesian method

Compute a sparse inverse solution using the Gamma-MAP empirical Bayesian method

Compute sparse inverse solution with mixed norm: MxNE and irMxNE

Compute sparse inverse solution with mixed norm: MxNE and irMxNE

Compute source power estimate by projecting the covariance with MNE

Compute source power estimate by projecting the covariance with MNE

Compute Rap-Music on evoked data

Compute Rap-Music on evoked data

Compute MxNE with time-frequency sparse prior

Compute MxNE with time-frequency sparse prior

Compute Trap-Music on evoked data

Compute Trap-Music on evoked data

Brainstorm raw (median nerve) dataset

Brainstorm raw (median nerve) dataset

Kernel OPM phantom data

Kernel OPM phantom data

Optically pumped magnetometer (OPM) data

Optically pumped magnetometer (OPM) data

From raw data to dSPM on SPM Faces dataset

From raw data to dSPM on SPM Faces dataset
plot_field(surf_maps, time=None, time_label='t = %0.0f ms', n_jobs=None, fig=None, vmax=None, n_contours=21, *, show_density=True, alpha=None, interpolation='nearest', interaction='terrain', time_viewer='auto', verbose=None)[source]#

Plot MEG/EEG fields on head surface and helmet in 3D.

Parameters:
surf_mapslist

The surface mapping information obtained with make_field_map.

timefloat | None

The time point at which the field map shall be displayed. If None, the average peak latency (across sensor types) is used.

time_labelstr | None

How to print info about the time instant visualized.

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_config context manager that sets another value for n_jobs.

figFigure3D | mne.viz.Brain | None

If None (default), a new figure will be created, otherwise it will plot into the given figure.

New in v0.20.

New in v1.4: fig can also be a Brain figure.

vmaxfloat | dict | None

Maximum intensity. Can be a dictionary with two entries "eeg" and "meg" to specify separate values for EEG and MEG fields respectively. Can be None to use the maximum value of the data.

New in v0.21.

New in v1.4: vmax can be a dictionary to specify separate values for EEG and MEG fields.

n_contoursint

The number of contours.

New in v0.21.

show_densitybool

Whether to draw the field density as an overlay on top of the helmet/head surface. Defaults to True.

New in v1.6.

alphafloat | dict | None

Opacity of the meshes (between 0 and 1). Can be a dictionary with two entries "eeg" and "meg" to specify separate values for EEG and MEG fields respectively. Can be None to use 1.0 when a single field map is shown, or dict(eeg=1.0, meg=0.5) when both field maps are shown.

New in v1.4.

interpolationstr | None

Interpolation method (scipy.interpolate.interp1d parameter). Must be one of 'linear', 'nearest', 'zero', 'slinear', 'quadratic' or 'cubic'.

New in v1.6.

interaction‘trackball’ | ‘terrain’

How interactions with the scene via an input device (e.g., mouse or trackpad) modify the camera position. If 'terrain', one axis is fixed, enabling “turntable-style” rotations. If 'trackball', movement along all axes is possible, which provides more freedom of movement, but you may incidentally perform unintentional rotations along some axes. Defaults to 'terrain'.

New in v1.1.

time_viewerbool | str

Display time viewer GUI. Can also be "auto", which will mean True if there is more than one time point and False otherwise.

New in v1.6.

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:
figFigure3D | mne.viz.EvokedField

Without the time viewer active, the figure is returned. With the time viewer active, an object is returned that can be used to control different aspects of the figure.

Examples using plot_field:

Visualizing Evoked data

Visualizing Evoked data

Plot the MNE brain and helmet

Plot the MNE brain and helmet
plot_image(picks=None, exclude='bads', unit=True, show=True, clim=None, xlim='tight', proj=False, units=None, scalings=None, titles=None, axes=None, cmap='RdBu_r', colorbar=True, mask=None, mask_style=None, mask_cmap='Greys', mask_alpha=0.25, time_unit='s', show_names=None, group_by=None, sphere=None)[source]#

Plot evoked data as images.

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. This parameter can also be used to set the order the channels are shown in, as the channel image is sorted by the order of picks.

excludelist of str | ‘bads’

Channels names to exclude from being shown. If ‘bads’, the bad channels are excluded.

unitbool

Scale plot with channel (SI) unit.

showbool

Show figure if True.

climdict | None

Color limits for plots (after scaling has been applied). e.g. clim = dict(eeg=[-20, 20]). Valid keys are eeg, mag, grad, misc. If None, the clim parameter for each channel equals the pyplot default.

xlim‘tight’ | tuple | None

X limits for plots.

projbool | ‘interactive’

If true SSP projections are applied before display. If ‘interactive’, a check box for reversible selection of SSP projection vectors will be shown.

unitsdict | None

The units of the channel types used for axes labels. If None, defaults to dict(eeg='µV', grad='fT/cm', mag='fT').

scalingsdict | None

The scalings of the channel types to be applied for plotting. If None,` defaults to dict(eeg=1e6, grad=1e13, mag=1e15).

titlesdict | None

The titles associated with the channels. If None, defaults to dict(eeg='EEG', grad='Gradiometers', mag='Magnetometers').

axesinstance of Axes | list | dict | None

The axes to plot to. If list, the list must be a list of Axes of the same length as the number of channel types. If instance of Axes, there must be only one channel type plotted. If group_by is a dict, this cannot be a list, but it can be a dict of lists of axes, with the keys matching those of group_by. In that case, the provided axes will be used for the corresponding groups. Defaults to None.

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

Colormap. 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 scale. Up and down arrows can be used to change the colormap. If ‘interactive’, translates to ('RdBu_r', True). Defaults to 'RdBu_r'.

colorbarbool

If True, plot a colorbar. Defaults to True.

New in v0.16.

maskndarray | None

An array of booleans of the same shape as the data. Entries of the data that correspond to False in the mask are masked (see do_mask below). Useful for, e.g., masking for statistical significance.

New in v0.16.

mask_styleNone | ‘both’ | ‘contour’ | ‘mask’

If mask is not None: if ‘contour’, a contour line is drawn around the masked areas (True in mask). If ‘mask’, entries not True in mask are shown transparently. If ‘both’, both a contour and transparency are used. If None, defaults to ‘both’ if mask is not None, and is ignored otherwise.

New in v0.16.

mask_cmapmatplotlib colormap | (colormap, bool) | ‘interactive’

The colormap chosen for masked parts of the image (see below), if mask is not None. If None, cmap is reused. Defaults to Greys. Not interactive. Otherwise, as cmap.

mask_alphafloat

A float between 0 and 1. If mask is not None, this sets the alpha level (degree of transparency) for the masked-out segments. I.e., if 0, masked-out segments are not visible at all. Defaults to .25.

New in v0.16.

time_unitstr

The units for the time axis, can be “ms” or “s” (default).

New in v0.16.

show_namesbool | ‘auto’ | ‘all’

Determines if channel names should be plotted on the y axis. If False, no names are shown. If True, ticks are set automatically by matplotlib and the corresponding channel names are shown. If “all”, all channel names are shown. If “auto”, is set to False if picks is None, to True if picks contains 25 or more entries, or to “all” if picks contains fewer than 25 entries.

group_byNone | dict

If a dict, the values must be picks, and axes must also be a dict with matching keys, or None. If axes is None, one figure and one axis will be created for each entry in group_by.Then, for each entry, the picked channels will be plotted to the corresponding axis. If titles are None, keys will become plot titles. This is useful for e.g. ROIs. Each entry must contain only one channel type. For example:

group_by=dict(Left_ROI=[1, 2, 3, 4], Right_ROI=[5, 6, 7, 8])

If None, all picked channels are plotted to the same axis.

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.

Returns:
figinstance of matplotlib.figure.Figure

Figure containing the images.

Examples using plot_image:

Visualizing Evoked data

Visualizing Evoked data

Visualising statistical significance thresholds on EEG data

Visualising statistical significance thresholds on EEG data

Analysing continuous features with binning and regression in sensor space

Analysing continuous features with binning and regression in sensor space
plot_joint(times='peaks', title='', picks=None, exclude='bads', show=True, ts_args=None, topomap_args=None)[source]#

Plot evoked data as butterfly plot and add topomaps for time points.

Note

Axes to plot in can be passed by the user through ts_args or topomap_args. In that case both ts_args and topomap_args axes have to be used. Be aware that when the axes are provided, their position may be slightly modified.

Parameters:
timesfloat | array of float | “auto” | “peaks”

The time point(s) to plot. If "auto", 5 evenly spaced topographies between the first and last time instant will be shown. If "peaks", finds time points automatically by checking for 3 local maxima in Global Field Power. Defaults to "peaks".

titlestr | None

The title. If None, suppress printing channel type title. If an empty string, a default title is created. Defaults to ‘’. If custom axes are passed make sure to set title=None, otherwise some of your axes may be removed during placement of the title axis.

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.

excludeNone | list of str | ‘bads’

Channels names to exclude from being shown. If 'bads', the bad channels are excluded. Defaults to None.

showbool

Show figure if True. Defaults to True.

ts_argsNone | dict

A dict of kwargs that are forwarded to mne.Evoked.plot() to style the butterfly plot. If they are not in this dict, the following defaults are passed: spatial_colors=True, zorder='std'. show and exclude are illegal. If None, no customizable arguments will be passed. Defaults to None.

topomap_argsNone | dict

A dict of kwargs that are forwarded to mne.Evoked.plot_topomap() to style the topomaps. If it is not in this dict, outlines='head' will be passed. show, times, colorbar are illegal. If None, no customizable arguments will be passed. Defaults to None.

Returns:
figinstance of matplotlib.figure.Figure | list

The figure object containing the plot. If evoked has multiple channel types, a list of figures, one for each channel type, is returned.

Notes

New in v0.12.0.

Examples using plot_joint:

Overview of MEG/EEG analysis with MNE-Python

Overview of MEG/EEG analysis with MNE-Python

Overview of artifact detection

Overview of artifact detection

Repairing artifacts with ICA

Repairing artifacts with ICA

Repairing artifacts with SSP

Repairing artifacts with SSP

EEG analysis - Event-Related Potentials (ERPs)

EEG analysis - Event-Related Potentials (ERPs)

Source reconstruction using an LCMV beamformer

Source reconstruction using an LCMV beamformer

EEG source localization given electrode locations on an MRI

EEG source localization given electrode locations on an MRI

KIT phantom dataset tutorial

KIT phantom dataset tutorial

Visualising statistical significance thresholds on EEG data

Visualising statistical significance thresholds on EEG data

Decoding (MVPA)

Decoding (MVPA)

Transform EEG data using current source density (CSD)

Transform EEG data using current source density (CSD)

Single trial linear regression analysis with the LIMO dataset

Single trial linear regression analysis with the LIMO dataset
plot_projs_topomap(ch_type=None, *, sensors=True, show_names=False, 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=False, cbar_fmt='%3.1f', units=None, axes=None, show=True)[source]#

Plot SSP vector.

Parameters:
ch_type‘mag’ | ‘grad’ | ‘planar1’ | ‘planar2’ | ‘eeg’ | None | list

The channel type to plot. For 'grad', the gradiometers are collected in pairs and the RMS for each pair is plotted. If None it will return all channel types present.. If a list of ch_types is provided, it will return multiple figures. Defaults to None.

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.

New in v1.2.

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.

New in v0.20.

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

resint

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

sizefloat

Side length of each subplot in inches. Only applies when plotting multiple topomaps at a time.

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 projectors of the same channel type (instead of separately for each projector), using the min/max of the data for that channel type. If vlim is "joint", info must not be None. 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.

New in v1.2.

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.

New in v1.2.

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.

New in v1.2.

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 number of projectors. Default is None.

showbool

Show the figure if True.

Returns:
figinstance of Figure

Figure distributing one image per channel across sensor topography.

plot_psd(fmin=0, fmax=inf, tmin=None, tmax=None, picks=None, proj=False, *, method='auto', average=False, dB=True, estimate='power', xscale='linear', area_mode='std', area_alpha=0.33, color='black', line_alpha=None, spatial_colors=True, sphere=None, exclude='bads', ax=None, show=True, n_jobs=1, verbose=None, **method_kw)[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:
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.

method'welch' | 'multitaper' | 'auto'

Spectral estimation method. 'welch' uses Welch’s method [1], 'multitaper' uses DPSS tapers [2]. 'auto' (default) uses Welch’s method for continuous data and multitaper for Epochs or Evoked data.

averagebool

If False, the PSDs of all channels is displayed. No averaging is done and parameters area_mode and area_alpha are ignored. When False, it is possible to paint an area (hold left mouse button and drag) to plot a topomap.

dBbool

Plot Power Spectral Density (PSD), in units (amplitude**2/Hz (dB)) if dB=True, and estimate='power' or estimate='auto'. Plot PSD in units (amplitude**2/Hz) if dB=False and, estimate='power'. Plot Amplitude Spectral Density (ASD), in units (amplitude/sqrt(Hz)), if dB=False and estimate='amplitude' or estimate='auto'. Plot ASD, in units (amplitude/sqrt(Hz) (dB)), if dB=True and estimate='amplitude'.

estimatestr, {‘power’, ‘amplitude’}

Can be “power” for power spectral density (PSD; default), “amplitude” for amplitude spectrum density (ASD).

xscale‘linear’ | ‘log’

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

area_modestr | None

Mode for plotting area. If ‘std’, the mean +/- 1 STD (across channels) will be plotted. If ‘range’, the min and max (across channels) will be plotted. Bad channels will be excluded from these calculations. If None, no area will be plotted. If average=False, no area is plotted.

area_alphafloat

Alpha for the area.

colorstr | tuple

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

line_alphafloat | None

Alpha for the PSD line. Can be None (default) to use 1.0 when average=True and 0.1 when average=False.

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.

New in v0.22.0.

excludelist of str | ‘bads’

Channels names to exclude from being shown. If ‘bads’, the bad channels are excluded. Pass an empty list to plot all channels (including channels marked “bad”, if any).

New in v0.24.0.

axinstance 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 number of channel types present in the object.. Default is None.

showbool

Show the figure if True.

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_config 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. Note that for Welch method if n_fft is unspecified its default will be the smaller of 2048 or the number of available time samples (taking into account tmin and tmax), not 256 as in psd_array_welch().

Returns:
figinstance of Figure

Figure with frequency spectra of the data channels.

Notes

This method exists to support legacy code; for new code the preferred idiom is inst.compute_psd().plot() (where inst is an instance of Raw, Epochs, or Evoked).

plot_psd_topo(tmin=None, tmax=None, fmin=0, fmax=100, proj=False, *, method='auto', dB=True, layout=None, color='w', fig_facecolor='k', axis_facecolor='k', axes=None, block=False, show=True, n_jobs=None, verbose=None, **method_kw)[source]#

Warning

LEGACY: New code should use .compute_psd().plot_topo().

Plot power spectral density, separately for each channel.

Parameters:
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).

fmin, fmaxfloat

The lower- and upper-bound on frequencies of interest. Default is fmin=0, fmax=100.

projbool

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

method'welch' | 'multitaper' | 'auto'

Spectral estimation method. 'welch' uses Welch’s method [1], 'multitaper' uses DPSS tapers [2]. 'auto' (default) uses Welch’s method for continuous data and multitaper for Epochs or Evoked data.

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.

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_config 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. Note that for Welch method if n_fft is unspecified its default will be the smaller of 2048 or the number of available time samples (taking into account tmin and tmax), not 256 as in psd_array_welch(). Defaults to dict(n_fft=2048).

Returns:
figinstance of matplotlib.figure.Figure

Figure distributing one image per channel across sensor topography.

plot_psd_topomap(bands=None, tmin=None, tmax=None, ch_type=None, *, proj=False, method='auto', normalize=False, agg_fun=None, dB=False, sensors=True, show_names=False, mask=None, mask_params=None, contours=0, 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, n_jobs=None, verbose=None, **method_kw)[source]#

Warning

LEGACY: New code should use .compute_psd().plot_topomap().

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.

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).

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.

projbool

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

method'welch' | 'multitaper' | 'auto'

Spectral estimation method. 'welch' uses Welch’s method [1], 'multitaper' uses DPSS tapers [2]. 'auto' (default) uses Welch’s method for continuous data and multitaper for Epochs or Evoked data.

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.

New in v1.2.

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.

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_config 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. Note that for Welch method if n_fft is unspecified its default will be the smaller of 2048 or the number of available time samples (taking into account tmin and tmax), not 256 as in psd_array_welch().

Returns:
figinstance of Figure

Figure showing one scalp topography per frequency band.

plot_sensors(kind='topomap', ch_type=None, title=None, show_names=False, ch_groups=None, to_sphere=True, axes=None, block=False, show=True, sphere=None, *, verbose=None)[source]#

Plot sensor positions.

Parameters:
kindstr

Whether to plot the sensors as 3d, topomap or as an interactive sensor selection dialog. Available options ‘topomap’, ‘3d’, ‘select’. If ‘select’, a set of channels can be selected interactively by using lasso selector or clicking while holding control key. The selected channels are returned along with the figure instance. Defaults to ‘topomap’.

ch_typeNone | str

The channel type to plot. Available options 'mag', 'grad', 'eeg', 'seeg', 'dbs', 'ecog', 'all'. If 'all', all the available mag, grad, eeg, seeg, dbs, and ecog channels are plotted. If None (default), then channels are chosen in the order given above.

titlestr | None

Title for the figure. If None (default), equals to 'Sensor positions (%s)' % ch_type.

show_namesbool | array of str

Whether to display all channel names. If an array, only the channel names in the array are shown. Defaults to False.

ch_groups‘position’ | array of shape (n_ch_groups, n_picks) | None

Channel groups for coloring the sensors. If None (default), default coloring scheme is used. If ‘position’, the sensors are divided into 8 regions. See order kwarg of mne.viz.plot_raw(). If array, the channels are divided by picks given in the array.

New in v0.13.0.

to_spherebool

Whether to project the 3d locations to a sphere. When False, the sensor array appears similar as to looking downwards straight above the subject’s head. Has no effect when kind=’3d’. Defaults to True.

New in v0.14.0.

axesinstance of Axes | instance of Axes3D | None

Axes to draw the sensors to. If kind='3d', axes must be an instance of Axes3D. If None (default), a new axes will be created.

New in v0.13.0.

blockbool

Whether to halt program execution until the figure is closed. Defaults to False.

New in v0.13.0.

showbool

Show figure if True. Defaults to 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.

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:
figinstance of Figure

Figure containing the sensor topography.

selectionlist

A list of selected channels. Only returned if kind=='select'.

Notes

This function plots the sensor locations from the info structure using matplotlib. For drawing the sensors using PyVista see mne.viz.plot_alignment().

New in v0.12.0.

plot_topo(layout=None, layout_scale=0.945, color=None, border='none', ylim=None, scalings=None, title=None, proj=False, vline=(0.0,), fig_background=None, merge_grads=False, legend=True, axes=None, background_color='w', noise_cov=None, exclude='bads', show=True)[source]#

Plot 2D topography of evoked responses.

Clicking on the plot of an individual sensor opens a new figure showing the evoked response for the selected sensor.

Parameters:
layoutinstance of Layout | None

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

layout_scalefloat

Scaling factor for adjusting the relative size of the layout on the canvas.

colorlist of color | color | None

Everything matplotlib accepts to specify colors. If not list-like, the color specified will be repeated. If None, colors are automatically drawn.

borderstr

Matplotlib borders style to be used for each sensor plot.

ylimdict | None

Y-axis limits for plots (after scaling has been applied). dict keys should match channel types; valid keys are for instance eeg, mag, grad, misc, csd, .. (example: ylim=dict(eeg=[-20, 20])). If None, the y-axis limits will be set automatically by matplotlib. Defaults to None.

scalingsdict | None

The scalings of the channel types to be applied for plotting. If None,` defaults to dict(eeg=1e6, grad=1e13, mag=1e15).

titlestr

Title of the figure.

projbool | 'interactive'

If true SSP projections are applied before display. If 'interactive', a check box for reversible selection of SSP projection vectors will be shown.

vlinelist of float | float | None

The values at which to show a vertical line.

fig_backgroundNone | ndarray

A background image for the figure. This must work with a call to plt.imshow. Defaults to None.

merge_gradsbool

Whether to use RMS value of gradiometer pairs. Only works for Neuromag data. Defaults to False.

legendbool | int | str | tuple

If True, create a legend based on evoked.comment. If False, disable the legend. Otherwise, the legend is created and the parameter value is passed as the location parameter to the matplotlib legend call. It can be an integer (e.g. 0 corresponds to upper right corner of the plot), a string (e.g. 'upper right'), or a tuple (x, y coordinates of the lower left corner of the legend in the axes coordinate system). See matplotlib documentation for more details.

axesinstance of matplotlib Axes | None

Axes to plot into. If None, axes will be created.

background_colorcolor

Background color. Typically 'k' (black) or 'w' (white; default).

New in v0.15.0.

noise_covinstance of Covariance | str | None

Noise covariance used to whiten the data while plotting. Whitened data channel names are shown in italic. Can be a string to load a covariance from disk.

New in v0.16.0.

excludelist of str | 'bads'

Channels names to exclude from the plot. If 'bads', the bad channels are excluded. By default, exclude is set to 'bads'.

showbool

Show figure if True.

Returns:
figinstance of matplotlib.figure.Figure

Images of evoked responses at sensor locations.

Notes

New in v0.10.0.

Examples using plot_topo:

Overview of MEG/EEG analysis with MNE-Python

Overview of MEG/EEG analysis with MNE-Python

Visualizing Evoked data

Visualizing Evoked data

Plotting whitened data

Plotting whitened data
plot_topomap(times='auto', *, average=None, ch_type=None, scalings=None, proj=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='%3.1f', units=None, axes=None, time_unit='s', time_format=None, nrows=1, ncols='auto', show=True)[source]#

Plot topographic maps of specific time points of evoked data.

Parameters:
timesfloat | array of float | “auto” | “peaks” | “interactive”

The time point(s) to plot. If “auto”, the number of axes determines the amount of time point(s). If axes is also None, at most 10 topographies will be shown with a regular time spacing between the first and last time instant. If “peaks”, finds time points automatically by checking for local maxima in global field power. If “interactive”, the time can be set interactively at run-time by using a slider.

averagefloat | array_like of float, shape (n_times,) | None

The time window (in seconds) around a given time point to be used for averaging. For example, 0.2 would translate into a time window that starts 0.1 s before and ends 0.1 s after the given time point. If the time window exceeds the duration of the data, it will be clipped. Different time windows (one per time point) can be provided by passing an array-like object (e.g., [0.1, 0.2, 0.3]). If None (default), no averaging will take place.

Changed in version 1.1: Support for array-like input.

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

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

scalingsdict | float | None

The scalings of the channel types to be applied for plotting. If None, defaults to dict(eeg=1e6, grad=1e13, mag=1e15).

projbool | ‘interactive’ | ‘reconstruct’

If true SSP projections are applied before display. If 'interactive', a check box for reversible selection of SSP projection vectors will be shown. If 'reconstruct', projection vectors will be applied and then M/EEG data will be reconstructed via field mapping to reduce the signal bias caused by projection.

Changed in version 0.21: Support for ‘reconstruct’ was added.

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.

New in v0.18.

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

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).

New in v1.2.

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.

New in v1.2.

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.

unitsdict | str | None

The units to use for the colorbar label. Ignored if colorbar=False. If None and scalings=None the unit is automatically determined, otherwise 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 number of times provided (unless times is None). Default is None.

time_unitstr

The units for the time axis, can be “ms” or “s” (default).

New in v0.16.

time_formatstr | None

String format for topomap values. Defaults (None) to “%01d ms” if time_unit='ms', “%0.3f s” if time_unit='s', and “%g” otherwise. Can be an empty string to omit the time label.

nrows, ncolsint | ‘auto’

The number of rows and columns of topographies to plot. If either nrows or ncols is 'auto', the necessary number will be inferred. Defaults to nrows=1, ncols='auto'. Ignored when times == ‘interactive’.

New in v0.20.

showbool

Show the figure if True.

Returns:
figinstance of matplotlib.figure.Figure

The figure.

Notes

When existing axes are provided and colorbar=True, note that the colorbar scale will only accurately reflect topomaps that are generated in the same call as the colorbar. Note also that the colorbar will not be resized automatically when axes are provided; use Matplotlib’s axes.set_position() method or gridspec interface to adjust the colorbar size yourself.

When time=="interactive", the figure will publish and subscribe to the following UI events:

Examples using plot_topomap:

Overview of MEG/EEG analysis with MNE-Python

Overview of MEG/EEG analysis with MNE-Python

Working with CTF data: the Brainstorm auditory dataset

Working with CTF data: the Brainstorm auditory dataset

Overview of artifact detection

Overview of artifact detection

Repairing artifacts with SSP

Repairing artifacts with SSP

Preprocessing functional near-infrared spectroscopy (fNIRS) data

Preprocessing functional near-infrared spectroscopy (fNIRS) data

Regression-based baseline correction

Regression-based baseline correction

Auto-generating Epochs metadata

Auto-generating Epochs metadata

EEG analysis - Event-Related Potentials (ERPs)

EEG analysis - Event-Related Potentials (ERPs)

Source localization with equivalent current dipole (ECD) fit

Source localization with equivalent current dipole (ECD) fit

Source localization with MNE, dSPM, sLORETA, and eLORETA

Source localization with MNE, dSPM, sLORETA, and eLORETA

Spatiotemporal permutation F-test on full sensor data

Spatiotemporal permutation F-test on full sensor data

Using the event system to link figures

Using the event system to link figures

Transform EEG data using current source density (CSD)

Transform EEG data using current source density (CSD)

Maxwell filter data with movement compensation

Maxwell filter data with movement compensation

Remap MEG channel types

Remap MEG channel types

Plotting topographic maps of evoked data

Plotting topographic maps of evoked data

Permutation T-test on sensor data

Permutation T-test on sensor data

XDAWN Decoding From EEG data

XDAWN Decoding From EEG data

Compute effect-matched-spatial filtering (EMS)

Compute effect-matched-spatial filtering (EMS)

Linear classifier on sensor data with plot patterns and filters

Linear classifier on sensor data with plot patterns and filters

Compute Spectro-Spatial Decomposition (SSD) spatial filters

Compute Spectro-Spatial Decomposition (SSD) spatial filters

Compute source power estimate by projecting the covariance with MNE

Compute source power estimate by projecting the covariance with MNE

Brainstorm raw (median nerve) dataset

Brainstorm raw (median nerve) dataset
plot_white(noise_cov, show=True, rank=None, time_unit='s', sphere=None, axes=None, *, spatial_colors='auto', verbose=None)[source]#

Plot whitened evoked response.

Plots the whitened evoked response and the whitened GFP as described in [5]. This function is especially useful for investigating noise covariance properties to determine if data are properly whitened (e.g., achieving expected values in line with model assumptions, see Notes below).

Parameters:
noise_covlist | instance of Covariance | path-like

The noise covariance. Can be a string to load a covariance from disk.

showbool

Show figure if True.

rankNone | ‘info’ | ‘full’ | dict

This controls the rank computation that can be read from the measurement info or estimated from the data. When a noise covariance is used for whitening, this should reflect the rank of that covariance, otherwise amplification of noise components can occur in whitening (e.g., often during source localization).

None

The rank will be estimated from the data after proper scaling of different channel types.

'info'

The rank is inferred from info. If data have been processed with Maxwell filtering, the Maxwell filtering header is used. Otherwise, the channel counts themselves are used. In both cases, the number of projectors is subtracted from the (effective) number of channels in the data. For example, if Maxwell filtering reduces the rank to 68, with two projectors the returned value will be 66.

'full'

The rank is assumed to be full, i.e. equal to the number of good channels. If a Covariance is passed, this can make sense if it has been (possibly improperly) regularized without taking into account the true data rank.

dict

Calculate the rank only for a subset of channel types, and explicitly specify the rank for the remaining channel types. This can be extremely useful if you already know the rank of (part of) your data, for instance in case you have calculated it earlier.

This parameter must be a dictionary whose keys correspond to channel types in the data (e.g. 'meg', 'mag', 'grad', 'eeg'), and whose values are integers representing the respective ranks. For example, {'mag': 90, 'eeg': 45} will assume a rank of 90 and 45 for magnetometer data and EEG data, respectively.

The ranks for all channel types present in the data, but not specified in the dictionary will be estimated empirically. That is, if you passed a dataset containing magnetometer, gradiometer, and EEG data together with the dictionary from the previous example, only the gradiometer rank would be determined, while the specified magnetometer and EEG ranks would be taken for granted.

The default is None.

time_unitstr

The units for the time axis, can be “ms” or “s” (default).

New in v0.16.

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.

axeslist | None

List of axes to plot into.

New in v0.21.0.

spatial_colorsbool | ‘auto’

If True, the lines are color coded by mapping physical sensor coordinates into color values. Spatially similar channels will have similar colors. Bad channels will be dotted. If False, the good channels are plotted black and bad channels red. If 'auto', uses True if channel locations are present, and False if channel locations are missing or if the data contains only a single channel. Defaults to 'auto'.

New in v1.8.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.

Returns:
figinstance of matplotlib.figure.Figure

The figure object containing the plot.

See also

mne.Evoked.plot

Notes

If baseline signals match the assumption of Gaussian white noise, values should be centered at 0, and be within 2 standard deviations (±1.96) for 95% of the time points. For the global field power (GFP), we expect it to fluctuate around a value of 1.

If one single covariance object is passed, the GFP panel (bottom) will depict different sensor types. If multiple covariance objects are passed as a list, the left column will display the whitened evoked responses for each channel based on the whitener from the noise covariance that has the highest log-likelihood. The left column will depict the whitened GFPs based on each estimator separately for each sensor type. Instead of numbers of channels the GFP display shows the estimated rank. Note. The rank estimation will be printed by the logger (if verbose=True) for each noise covariance estimator that is passed.

References

[1]

Engemann D. and Gramfort A. (2015) Automated model selection in covariance estimation and spatial whitening of MEG and EEG signals, vol. 108, 328-342, NeuroImage.

Examples using plot_white:

Plotting whitened data

Plotting whitened data

Computing a covariance matrix

Computing a covariance matrix

Source localization with MNE, dSPM, sLORETA, and eLORETA

Source localization with MNE, dSPM, sLORETA, and eLORETA

Generate simulated raw data

Generate simulated raw data

Whitening evoked data with a noise covariance

Whitening evoked data with a noise covariance
property proj#

Whether or not projections are active.

rename_channels(mapping, allow_duplicates=False, *, verbose=None)[source]#

Rename channels.

Parameters:
mappingdict | callable()

A dictionary mapping the old channel to a new channel name e.g. {'EEG061' : 'EEG161'}. Can also be a callable function that takes and returns a string.

Changed in version 0.10.0: Support for a callable function.

allow_duplicatesbool

If True (default False), allow duplicates, which will automatically be renamed with -N at the end.

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

Returns:
instinstance of Raw | Epochs | Evoked

The instance (modified in place).

Changed in version 0.20: Return the instance.

Notes

New in v0.9.0.

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.

resample(sfreq, *, npad='auto', window='auto', n_jobs=None, pad='edge', method='fft', verbose=None)[source]#

Resample data.

If appropriate, an anti-aliasing filter is applied before resampling. See Resampling and decimating data for more information.

Note

Data must be loaded.

Parameters:
sfreqfloat

New sample rate to use.

npadint | str

Amount to pad the start and end of the data. Can also be "auto" to use a padding that will result in a power-of-two size (can be much faster).

windowstr | tuple

When method="fft", this is the frequency-domain window to use in resampling, and should be the same length as the signal; see scipy.signal.resample() for details. When method="polyphase", this is the time-domain linear-phase window to use after upsampling the signal; see scipy.signal.resample_poly() for details. The default "auto" will use "boxcar" for method="fft" and ("kaiser", 5.0) for method="polyphase".

n_jobsint | str

Number of jobs to run in parallel. Can be 'cuda' if cupy is installed properly.

padstr

The type of padding to use. When method="fft", supports all numpy.pad() mode options. Can also be "reflect_limited", which pads with a reflected version of each vector mirrored on the first and last values of the vector, followed by zeros. When method="polyphase", supports all modes of scipy.signal.upfirdn().

New in v0.15.

methodstr

Resampling method to use. Can be "fft" (default) or "polyphase" to use FFT-based on polyphase FIR resampling, respectively. These wrap to scipy.signal.resample() and scipy.signal.resample_poly(), respectively.

New in v1.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.

Returns:
instinstance of Epochs or Evoked

The resampled object.

Notes

For some data, it may be more accurate to use npad=0 to reduce artifacts. This is dataset dependent – check your data!

Examples using resample:

Filtering and resampling data

Filtering and resampling data

Permutation t-test on source data with spatio-temporal clustering

Permutation t-test on source data with spatio-temporal clustering

Repeated measures ANOVA on source data with spatio-temporal clustering

Repeated measures ANOVA on source data with spatio-temporal clustering
save(fname, *, overwrite=False, verbose=None)[source]#

Save evoked data to a file.

Parameters:
fnamepath-like

The name of the file, which should end with -ave.fif(.gz) or _ave.fif(.gz).

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.

Notes

To write multiple conditions into a single file, use mne.write_evokeds.

Changed in version 0.23: Information on baseline correction will be stored with the data, and will be restored when reading again via mne.read_evokeds.

Examples using save:

Getting started with mne.Report

Getting started with mne.Report
savgol_filter(h_freq, verbose=None)[source]#

Filter the data using Savitzky-Golay polynomial method.

Parameters:
h_freqfloat

Approximate high cut-off frequency in Hz. Note that this is not an exact cutoff, since Savitzky-Golay filtering [6] is done using polynomial fits instead of FIR/IIR filtering. This parameter is thus used to determine the length of the window over which a 5th-order polynomial smoothing is used.

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 Epochs, Evoked or SourceEstimate

The object with the filtering applied.

Notes

For Savitzky-Golay low-pass approximation, see:

When working on SourceEstimates the sample rate of the original data is inferred from tstep.

New in v0.9.0.

References

Examples

>>> import mne
>>> from os import path as op
>>> evoked_fname = op.join(mne.datasets.sample.data_path(), 'MEG', 'sample', 'sample_audvis-ave.fif')  
>>> evoked = mne.read_evokeds(evoked_fname, baseline=(None, 0))[0]  
>>> evoked.savgol_filter(10.)  # low-pass at around 10 Hz 
>>> evoked.plot()  
set_channel_types(mapping, *, on_unit_change='warn', verbose=None)[source]#

Specify the sensor types of channels.

Parameters:
mappingdict

A dictionary mapping channel names to sensor types, e.g., {'EEG061': 'eog'}.

on_unit_change'raise' | 'warn' | 'ignore'

What to do if the measurement unit of a channel is changed automatically to match the new sensor type.

New in v1.4.

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 | Evoked

The instance (modified in place).

Changed in version 0.20: Return the instance.

Notes

The following sensor types are accepted:

bio, chpi, csd, dbs, dipole, ecg, ecog, eeg, emg, eog, exci, eyegaze, fnirs_cw_amplitude, fnirs_fd_ac_amplitude, fnirs_fd_phase, fnirs_od, gof, gsr, hbo, hbr, ias, misc, pupil, ref_meg, resp, seeg, stim, syst, temperature.

When working with eye-tracking data, see mne.preprocessing.eyetracking.set_channel_types_eyetrack().

New in v0.9.0.

set_eeg_reference(ref_channels='average', projection=False, ch_type='auto', forward=None, *, joint=False, verbose=None)[source]#

Specify which reference to use for EEG data.

Use this function to explicitly specify the desired reference for EEG. This can be either an existing electrode or a new virtual channel. This function will re-reference the data according to the desired reference.

Parameters:
ref_channelslist of str | str

Can be:

  • The name(s) of the channel(s) used to construct the reference.

  • 'average' to apply an average reference (default)

  • 'REST' to use the Reference Electrode Standardization Technique infinity reference [7].

  • An empty list, in which case MNE will not attempt any re-referencing of the data

projectionbool

If ref_channels='average' this argument specifies if the average reference should be computed as a projection (True) or not (False; default). If projection=True, the average reference is added as a projection and is not applied to the data (it can be applied afterwards with the apply_proj method). If projection=False, the average reference is directly applied to the data. If ref_channels is not 'average', projection must be set to False (the default in this case).

ch_typelist of str | str

The name of the channel type to apply the reference to. Valid channel types are 'auto', 'eeg', 'ecog', 'seeg', 'dbs'. If 'auto', the first channel type of eeg, ecog, seeg or dbs that is found (in that order) will be selected.

New in v0.19.

Changed in version 1.2: list-of-str is now supported with projection=True.

forwardinstance of Forward | None

Forward solution to use. Only used with ref_channels='REST'.

New in v0.21.

jointbool

How to handle list-of-str ch_type. If False (default), one projector is created per channel type. If True, one projector is created across all channel types. This is only used when projection=True.

New in v1.2.

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 | Evoked

Data with EEG channels re-referenced. If ref_channels='average' and projection=True a projection will be added instead of directly re-referencing the data.

See also

mne.set_bipolar_reference

Convenience function for creating bipolar references.

Notes

Some common referencing schemes and the corresponding value for the ref_channels parameter:

  • Average reference:

    A new virtual reference electrode is created by averaging the current EEG signal by setting ref_channels='average'. Bad EEG channels are automatically excluded if they are properly set in info['bads'].

  • A single electrode:

    Set ref_channels to a list containing the name of the channel that will act as the new reference, for example ref_channels=['Cz'].

  • The mean of multiple electrodes:

    A new virtual reference electrode is created by computing the average of the current EEG signal recorded from two or more selected channels. Set ref_channels to a list of channel names, indicating which channels to use. For example, to apply an average mastoid reference, when using the 10-20 naming scheme, set ref_channels=['M1', 'M2'].

  • REST

    The given EEG electrodes are referenced to a point at infinity using the lead fields in forward, which helps standardize the signals.

  1. If a reference is requested that is not the average reference, this function removes any pre-existing average reference projections.

  2. During source localization, the EEG signal should have an average reference.

  3. In order to apply a reference, the data must be preloaded. This is not necessary if ref_channels='average' and projection=True.

  4. For an average or REST reference, bad EEG channels are automatically excluded if they are properly set in info['bads'].

New in v0.9.0.

References

set_meas_date(meas_date)[source]#

Set the measurement start date.

Parameters:
meas_datedatetime | float | tuple | None

The new measurement date. If datetime object, it must be timezone-aware and in UTC. A tuple of (seconds, microseconds) or float (alias for (meas_date, 0)) can also be passed and a datetime object will be automatically created. If None, will remove the time reference.

Returns:
instinstance of Raw | Epochs | Evoked

The modified raw instance. Operates in place.

Notes

If you want to remove all time references in the file, call mne.io.anonymize_info(inst.info) after calling inst.set_meas_date(None).

New in v0.20.

set_montage(montage, match_case=True, match_alias=False, on_missing='raise', verbose=None)[source]#

Set EEG/sEEG/ECoG/DBS/fNIRS channel positions and digitization points.

Parameters:
montageNone | str | DigMontage

A montage containing channel positions. If a string or DigMontage is specified, the existing channel information will be updated with the channel positions from the montage. Valid strings are the names of the built-in montages that ship with MNE-Python; you can list those via mne.channels.get_builtin_montages(). If None (default), the channel positions will be removed from the Info.

match_casebool

If True (default), channel name matching will be case sensitive.

New in v0.20.

match_aliasbool | dict

Whether to use a lookup table to match unrecognized channel location names to their known aliases. If True, uses the mapping in mne.io.constants.CHANNEL_LOC_ALIASES. If a dict is passed, it will be used instead, and should map from non-standard channel names to names in the specified montage. Default is False.

New in v0.23.

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

Can be 'raise' (default) to raise an error, 'warn' to emit a warning, or 'ignore' to ignore when channels have missing coordinates.

New in v0.20.1.

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 | Evoked

The instance, modified in-place.

Notes

Warning

Only EEG/sEEG/ECoG/DBS/fNIRS channels can have their positions set using a montage. Other channel types (e.g., MEG channels) should have their positions defined properly using their data reading functions.

Warning

Applying a montage will only set locations of channels that exist at the time it is applied. This means when re-referencing make sure to apply the montage only after calling mne.add_reference_channels()

Examples using set_montage:

Working with sensor locations

Working with sensor locations
shift_time(tshift, relative=True)[source]#

Shift time scale in epoched or evoked data.

Parameters:
tshiftfloat

The (absolute or relative) time shift in seconds. If relative is True, positive tshift increases the time value associated with each sample, while negative tshift decreases it.

relativebool

If True, increase or decrease time values by tshift seconds. Otherwise, shift the time values such that the time of the first sample equals tshift.

Returns:
epochsMNE-object

The modified instance.

Notes

This method allows you to shift the time values associated with each data sample by an arbitrary amount. It does not resample the signal or change the data values in any way.

Examples using shift_time:

Shifting time-scale in evoked data

Shifting time-scale in evoked data

Brainstorm raw (median nerve) dataset

Brainstorm raw (median nerve) dataset
time_as_index(times, use_rounding=False)[source]#

Convert time to indices.

Parameters:
timeslist-like | float | int

List of numbers or a number representing points in time.

use_roundingbool

If True, use rounding (instead of truncation) when converting times to indices. This can help avoid non-unique indices.

Returns:
indexndarray

Indices corresponding to the times supplied.

Examples using time_as_index:

The Evoked data structure: evoked/averaged data

The Evoked data structure: evoked/averaged data

Compute sparse inverse solution with mixed norm: MxNE and irMxNE

Compute sparse inverse solution with mixed norm: MxNE and irMxNE
property times#

Time vector in seconds.

property tmax#

Last time point.

property tmin#

First time point.

to_data_frame(picks=None, index=None, scalings=None, copy=True, long_format=False, time_format=None, *, 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 “time” is added, unless index='time' (in which case time 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.

index‘time’ | None

Kind of index to use for the DataFrame. If None, a sequential integer index (pandas.RangeIndex) will be used. If 'time', a pandas.Index or pandas.TimedeltaIndex will be used (depending on the value of time_format). Defaults to None.

scalingsdict | None

Scaling factor applied to the channels picked. If None, defaults to dict(eeg=1e6, mag=1e15, grad=1e13) — i.e., converts EEG to µV, magnetometers to fT, and gradiometers to fT/cm.

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 time point and channel. For convenience, a ch_type column is added to facilitate subsetting the resulting DataFrame. Defaults to False.

time_formatstr | None

Desired time format. If None, no conversion is applied, and time values remain as float values in seconds. If 'ms', time values will be rounded to the nearest millisecond and converted to integers. If 'timedelta', time values will be converted to pandas.Timedelta values. Default is None.

New in v0.20.

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.

Examples using to_data_frame:

Working with ECoG data

Working with ECoG data

Examples using mne.Evoked#

Overview of MEG/EEG analysis with MNE-Python

Overview of MEG/EEG analysis with MNE-Python

Modifying data in-place

Modifying data in-place

The Info data structure

The Info data structure

Getting started with mne.Report

Getting started with mne.Report

Rejecting bad data spans and breaks

Rejecting bad data spans and breaks

Filtering and resampling data

Filtering and resampling data

Repairing artifacts with regression

Repairing artifacts with regression

Repairing artifacts with ICA

Repairing artifacts with ICA

The Evoked data structure: evoked/averaged data

The Evoked data structure: evoked/averaged data

Visualizing Evoked data

Visualizing Evoked data

EEG analysis - Event-Related Potentials (ERPs)

EEG analysis - Event-Related Potentials (ERPs)

The Spectrum and EpochsSpectrum classes: frequency-domain data

The Spectrum and EpochsSpectrum classes: frequency-domain data

Source localization with equivalent current dipole (ECD) fit

Source localization with equivalent current dipole (ECD) fit

The role of dipole orientations in distributed source localization

The role of dipole orientations in distributed source localization

Computing various MNE solutions

Computing various MNE solutions

Visualize source time courses (stcs)

Visualize source time courses (stcs)

Brainstorm Elekta phantom dataset tutorial

Brainstorm Elekta phantom dataset tutorial

KIT phantom dataset tutorial

KIT phantom dataset tutorial

Visualising statistical significance thresholds on EEG data

Visualising statistical significance thresholds on EEG data

Spatiotemporal permutation F-test on full sensor data

Spatiotemporal permutation F-test on full sensor data

Decoding (MVPA)

Decoding (MVPA)

Creating MNE-Python data structures from scratch

Creating MNE-Python data structures from scratch

Make figures more publication ready

Make figures more publication ready

Using the event system to link figures

Using the event system to link figures

Interpolate bad channels for MEG/EEG channels

Interpolate bad channels for MEG/EEG channels

Plot sensor denoising using oversampled temporal projection

Plot sensor denoising using oversampled temporal projection

Shifting time-scale in evoked data

Shifting time-scale in evoked data

Remap MEG channel types

Remap MEG channel types

Plotting with mne.viz.Brain

Plotting with mne.viz.Brain

Plotting topographic arrowmaps of evoked data

Plotting topographic arrowmaps of evoked data

Plotting topographic maps of evoked data

Plotting topographic maps of evoked data

Plot the MNE brain and helmet

Plot the MNE brain and helmet

Compute source power spectral density (PSD) of VectorView and OPM data

Compute source power spectral density (PSD) of VectorView and OPM data

Permutation T-test on sensor data

Permutation T-test on sensor data

Analysing continuous features with binning and regression in sensor space

Analysing continuous features with binning and regression in sensor space

Analysis of evoked response using ICA and PCA reduction techniques

Analysis of evoked response using ICA and PCA reduction techniques

XDAWN Decoding From EEG data

XDAWN Decoding From EEG data

Compute effect-matched-spatial filtering (EMS)

Compute effect-matched-spatial filtering (EMS)

Linear classifier on sensor data with plot patterns and filters

Linear classifier on sensor data with plot patterns and filters

Compute Spectro-Spatial Decomposition (SSD) spatial filters

Compute Spectro-Spatial Decomposition (SSD) spatial filters

Compute MNE-dSPM inverse solution on evoked data in volume source space

Compute MNE-dSPM inverse solution on evoked data in volume source space

Source localization with a custom inverse solver

Source localization with a custom inverse solver

Compute a sparse inverse solution using the Gamma-MAP empirical Bayesian method

Compute a sparse inverse solution using the Gamma-MAP empirical Bayesian method

Generate a functional label from source estimates

Generate a functional label from source estimates

Extracting the time series of activations in a label

Extracting the time series of activations in a label

Compute sparse inverse solution with mixed norm: MxNE and irMxNE

Compute sparse inverse solution with mixed norm: MxNE and irMxNE

Compute MNE inverse solution on evoked data with a mixed source space

Compute MNE inverse solution on evoked data with a mixed source space

Morph volumetric source estimate

Morph volumetric source estimate

Plot point-spread functions (PSFs) and cross-talk functions (CTFs)

Plot point-spread functions (PSFs) and cross-talk functions (CTFs)

Plot point-spread functions (PSFs) for a volume

Plot point-spread functions (PSFs) for a volume

Compute Rap-Music on evoked data

Compute Rap-Music on evoked data

Compute spatial resolution metrics in source space

Compute spatial resolution metrics in source space

Compute spatial resolution metrics to compare MEG with EEG+MEG

Compute spatial resolution metrics to compare MEG with EEG+MEG

Estimate data SNR using an inverse

Estimate data SNR using an inverse

Computing source space SNR

Computing source space SNR

Compute MxNE with time-frequency sparse prior

Compute MxNE with time-frequency sparse prior

Compute Trap-Music on evoked data

Compute Trap-Music on evoked data

Plotting the full vector-valued MNE solution

Plotting the full vector-valued MNE solution

HF-SEF dataset

HF-SEF dataset

Kernel OPM phantom data

Kernel OPM phantom data