mne.Evoked

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

Evoked data.

Parameters:

fname : string

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

condition : int, or str

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

proj : bool, optional

Apply SSP projection vectors

kind : str

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

allow_maxshield : bool | 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.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more).

Notes

Evoked objects contain a single condition only.

Attributes

ch_names Channel names.
data The data matrix.
info (dict) Measurement info.
nave (int) Number of averaged epochs.
kind (str) Type of data, either average or standard_error.
first (int) First time sample.
last (int) Last time sample.
comment (string) Comment on dataset. Can be the condition.
times (array) Array of time instants in seconds.
verbose (bool, str, int, or None.) See above.

Methods

__contains__(ch_type) Check channel type membership.
__hash__() Hash the object.
__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.
animate_topomap([ch_type, times, …]) Make animation of evoked data as topomap timeseries.
anonymize() Anonymize measurement information in place.
apply_baseline([baseline, verbose]) Baseline correct evoked data.
apply_proj() Apply the signal space projection (SSP) operators to the data.
as_type([ch_type, mode]) Compute virtual evoked using interpolated fields.
copy() Copy the instance of evoked.
crop([tmin, tmax]) Crop data to a given time interval.
decimate(decim[, offset]) Decimate the evoked data.
del_proj([idx]) Remove SSP projection vector.
detrend([order, picks]) Detrend data.
drop_channels(ch_names) Drop some channels.
get_peak([ch_type, tmin, tmax, mode, …]) Get location and latency of peak amplitude.
interpolate_bads([reset_bads, mode]) Interpolate bad MEG and EEG channels.
pick_channels(ch_names) Pick some channels.
pick_types([meg, eeg, stim, eog, ecg, emg, …]) Pick some channels by type and names.
plot([picks, exclude, unit, show, ylim, …]) Plot evoked data using butteryfly plots.
plot_field(surf_maps[, time, time_label, n_jobs]) 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, layout, axes]) Plot SSP vector.
plot_sensors([kind, ch_type, title, …]) Plot sensor positions.
plot_topo([layout, layout_scale, color, …]) Plot 2D topography of evoked responses.
plot_topomap([times, ch_type, layout, vmin, …]) Plot topographic maps of specific time points of evoked data.
plot_white(noise_cov[, show]) Plot whitened evoked response.
rename_channels(mapping) Rename channels.
resample(sfreq[, npad, window]) Resample data.
save(fname) Save dataset to file.
savgol_filter(h_freq[, copy]) Filter the data using Savitzky-Golay polynomial method.
set_channel_types(mapping) Define the sensor type of channels.
set_eeg_reference([ref_channels, verbose]) Specify which reference to use for EEG data.
set_montage(montage[, verbose]) Set EEG sensor configuration and head digitization.
shift_time(tshift[, relative]) Shift time scale in evoked data.
time_as_index(times[, use_rounding]) Convert time to indices.
to_data_frame([picks, index, scale_time, …]) Export data in tabular structure as a pandas DataFrame.
__contains__(ch_type)[source]

Check channel type membership.

Parameters:

ch_type : str

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

Returns:

in : bool

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
__hash__()[source]

Hash the object.

Returns:

hash : int

The hash

__neg__()[source]

Negate channel responses.

Returns:

evoked_neg : instance 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_list : list

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

force_update_info : bool

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

New in version 0.12.

Returns:

inst : instance of Raw, Epochs, or Evoked

The modified instance.

add_proj(projs, remove_existing=False, verbose=None)[source]

Add SSP projection vectors.

Parameters:

projs : list

List with projection vectors.

remove_existing : bool

Remove the projection vectors currently in the file.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more).

Returns:

self : instance of Raw | Epochs | Evoked

The data container.

animate_topomap(ch_type=’mag’, times=None, frame_rate=None, butterfly=False, blit=True, show=True)[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_type : str | None

Channel type to plot. Accepted data types: ‘mag’, ‘grad’, ‘eeg’. If None, first available channel type from (‘mag’, ‘grad’, ‘eeg’) is used. Defaults to None.

times : array of floats | None

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

frame_rate : int | None

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

butterfly : bool

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

blit : bool

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.

show : bool

Whether to show the animation. Defaults to True.

Returns:

fig : instance of matplotlib figure

The figure.

anim : instance of matplotlib FuncAnimation

Animation of the topomap.

Notes

New in version 0.12.0.

anonymize()[source]

Anonymize measurement information in place.

Reset ‘subject_info’, ‘meas_date’, ‘file_id’, and ‘meas_id’ keys if they exist in info.

Returns:

info : instance of Info

Measurement information for the dataset.

Notes

Operates in place.

New in version 0.13.0.

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

Baseline correct evoked data.

Parameters:

baseline : tuple of length 2

The time interval to apply baseline correction. If None do not apply it. If baseline is (a, b) the interval is between “a (s)” and “b (s)”. If a is None the beginning of the data is used and if b is None then b is set to the end of the interval. If baseline is equal to (None, None) all the time interval is used. Correction is applied by computing mean of the baseline period and subtracting it from the data. The baseline (a, b) includes both endpoints, i.e. all timepoints t such that a <= t <= b.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more).

Returns:

evoked : instance of Evoked

The baseline-corrected Evoked object.

Notes

Baseline correction can be done multiple times.

New in version 0.13.0.

apply_proj()[source]

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

Returns:

self : instance 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
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 ‘_virtual’ appended at the end of the names to emphasize that the data contained in them are interpolated.

Parameters:

ch_type : str

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

mode : str

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

Returns:

evoked : instance of mne.Evoked

The transformed evoked object containing only virtual channels.

Notes

New in version 0.9.0.

ch_names

Channel names.

compensation_grade

The current gradient compensation grade.

copy()[source]

Copy the instance of evoked.

Returns:evoked : instance of Evoked
crop(tmin=None, tmax=None)[source]

Crop data to a given time interval.

Parameters:

tmin : float | None

Start time of selection in seconds.

tmax : float | None

End time of selection in seconds.

Returns:

evoked : instance of Evoked

The cropped Evoked object.

Notes

Unlike Python slices, MNE time intervals include both their end points; crop(tmin, tmax) returns the interval tmin <= t <= tmax.

data

The data matrix.

decimate(decim, offset=0)[source]

Decimate the evoked data.

Note

No filtering is performed. To avoid aliasing, ensure your data are properly lowpassed.

Parameters:

decim : int

The amount to decimate data.

offset : int

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.

Returns:

evoked : instance of Evoked

The decimated Evoked object.

Notes

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

New in version 0.13.0.

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:

idx : int | list of int | str

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

Returns:

self : instance of Raw | Epochs | Evoked

detrend(order=1, picks=None)[source]

Detrend data.

This function operates in-place.

Parameters:

order : int

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

picks : array-like of int | None

If None only MEG, EEG, SEEG, ECoG and fNIRS channels are detrended.

Returns:

evoked : instance of Evoked

The detrended evoked object.

drop_channels(ch_names)[source]

Drop some channels.

Parameters:

ch_names : list

List of the names of the channels to remove.

Returns:

inst : instance of Raw, Epochs, or Evoked

The modified instance.

See also

pick_channels

Notes

New in version 0.9.0.

get_peak(ch_type=None, tmin=None, tmax=None, mode=’abs’, time_as_index=False, merge_grads=False)[source]

Get location and latency of peak amplitude.

Parameters:

ch_type : ‘mag’, ‘grad’, ‘eeg’, ‘seeg’, ‘ecog’, ‘hbo’, hbr’, ‘misc’, None # noqa

The channel type to use. Defaults to None. If more than one sensor Type is present in the data the channel type has to be explicitly set.

tmin : float | None

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

tmax : float | 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_index : bool

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

merge_grads : bool

If True, compute peak from merged gradiometer data.

Returns:

ch_name : str

The channel exhibiting the maximum response.

latency : float | int

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

interpolate_bads(reset_bads=True, mode=’accurate’)[source]

Interpolate bad MEG and EEG channels.

Operates in place.

Parameters:

reset_bads : bool

If True, remove the bads from info.

mode : str

Either ‘accurate’ or ‘fast’, determines the quality of the Legendre polynomial expansion used for interpolation of MEG channels.

Returns:

inst : instance of Raw, Epochs, or Evoked

The modified instance.

Notes

New in version 0.9.0.

pick_channels(ch_names)[source]

Pick some channels.

Parameters:

ch_names : list

The list of channels to select.

Returns:

inst : instance of Raw, Epochs, or Evoked

The modified instance.

See also

drop_channels

Notes

New in version 0.9.0.

pick_types(meg=True, 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, include=[], exclude=’bads’, selection=None)[source]

Pick some channels by type and names.

Parameters:

meg : bool | str

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

eeg : bool

If True include EEG channels.

stim : bool

If True include stimulus channels.

eog : bool

If True include EOG channels.

ecg : bool

If True include ECG channels.

emg : bool

If True include EMG channels.

ref_meg: bool | str

If True include CTF / 4D reference channels. If ‘auto’, the reference channels are only included if compensations are present.

misc : bool

If True include miscellaneous analog channels.

resp : bool

If True include response-trigger channel. For some MEG systems this is separate from the stim channel.

chpi : bool

If True include continuous HPI coil channels.

exci : bool

Flux excitation channel used to be a stimulus channel.

ias : bool

Internal Active Shielding data (maybe on Triux only).

syst : bool

System status channel information (on Triux systems only).

seeg : bool

Stereotactic EEG channels.

dipole : bool

Dipole time course channels.

gof : bool

Dipole goodness of fit channels.

bio : bool

Bio channels.

ecog : bool

Electrocorticography channels.

fnirs : bool | 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).

include : list of string

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

exclude : list of string | str

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

selection : list of string

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

Returns:

inst : instance of Raw, Epochs, or Evoked

The modified instance.

Notes

New in version 0.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=False, zorder=’unsorted’, selectable=True)[source]

Plot evoked data using butteryfly 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:

picks : array-like of int | None

The indices of channels to plot. If None show all.

exclude : list of str | ‘bads’

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

unit : bool

Scale plot with channel (SI) unit.

show : bool

Show figure if True.

ylim : dict | None

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

xlim : ‘tight’ | tuple | None

xlim for plots.

proj : bool | ‘interactive’

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

hline : list of floats | None

The values at which to show an horizontal line.

units : dict | None

The units of the channel types used for axes lables. If None, defaults to dict(eeg=’uV’, grad=’fT/cm’, mag=’fT’).

scalings : dict | None

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

titles : dict | None

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

axes : instance of Axis | 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.

gfp : bool | ‘only’

Plot GFP in green if True or “only”. If “only”, then the individual channel traces will not be shown.

window_title : str | None

The title to put at the top of the figure.

spatial_colors : bool

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. Defaults to False.

zorder : str | 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 version 0.13.0.

selectable : bool

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 version 0.13.0.

Returns:

fig : instance of matplotlib.figure.Figure

Figure containing the butterfly plots.

plot_field(surf_maps, time=None, time_label=’t = %0.0f ms’, n_jobs=1)[source]

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

Parameters:

surf_maps : list

The surface mapping information obtained with make_field_map.

time : float | None

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

time_label : str

How to print info about the time instant visualized.

n_jobs : int

Number of jobs to run in parallel.

Returns:

fig : instance of mlab.Figure

The mayavi figure.

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’)[source]

Plot evoked data as images.

Parameters:

picks : array-like of int | None

The indices of channels to plot. If None show all.

exclude : list of str | ‘bads’

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

unit : bool

Scale plot with channel (SI) unit.

show : bool

Show figure if True.

clim : dict | None

clim 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

xlim for plots.

proj : bool | ‘interactive’

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

units : dict | None

The units of the channel types used for axes lables. If None, defaults to dict(eeg=’uV’, grad=’fT/cm’, mag=’fT’).

scalings : dict | None

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

titles : dict | None

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

axes : instance of Axis | 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.

cmap : matplotlib 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’.

Returns:

fig : instance of matplotlib.figure.Figure

Figure containing the images.

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.

Parameters:

times : float | array of floats | “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”.

title : str | None

The title. If None, suppress printing channel type. Defaults to ”.

picks : array-like of int | None

The indices of channels to plot. If None show all. Defaults to None.

exclude : None | list of str | ‘bads’

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

show : bool

Show figure if True. Defaults to True.

ts_args : None | dict

A dict of kwargs that are forwarded to evoked.plot to style the butterfly plot. axes and show are ignored. If spatial_colors is not in this dict, spatial_colors=True, and (if it is not in the dict) zorder=’std’ will be passed. Defaults to None.

topomap_args : None | dict

A dict of kwargs that are forwarded to evoked.plot_topomap to style the topomaps. axes and show are ignored. If times is not in this dict, automatic peak detection is used. Beyond that, if None`, no customizable arguments will be passed. Defaults to ``None.

Returns:

fig : instance 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 version 0.12.0.

plot_projs_topomap(ch_type=None, layout=None, axes=None)[source]

Plot SSP vector.

Parameters:

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

The channel type to plot. For ‘grad’, the gradiometers are collec- ted in pairs and the RMS for each pair is plotted. If None (default), it will return all channel types present. If a list of ch_types is provided, it will return multiple figures.

layout : None | Layout | List of Layouts

Layout instance specifying sensor positions (does not need to be specified for Neuromag data). If possible, the correct layout file is inferred from the data; if no appropriate layout file was found, the layout is automatically generated from the sensor locations. Or a list of Layout if projections are from different sensor types.

axes : instance 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 projectors. If instance of Axes, there must be only one projector. Defaults to None.

Returns:

fig : instance of matplotlib figure

Figure distributing one image per channel across sensor topography.

plot_sensors(kind=’topomap’, ch_type=None, title=None, show_names=False, ch_groups=None, to_sphere=True, axes=None, block=False, show=True)[source]

Plot sensor positions.

Parameters:

kind : str

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_type : None | str

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

title : str | None

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

show_names : bool

Whether to display all channel names. Defaults to False.

ch_groups : ‘position’ | array of shape (ch_groups, 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 version 0.13.0.

to_sphere : bool

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 version 0.14.0.

axes : instance 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 version 0.13.0.

block : bool

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

New in version 0.13.0.

show : bool

Show figure if True. Defaults to True.

Returns:

fig : instance of matplotlib figure

Figure containing the sensor topography.

selection : list

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 mayavi see mne.viz.plot_trans().

New in version 0.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_facecolor=’k’, fig_background=None, axis_facecolor=’k’, font_color=’w’, merge_grads=False, legend=True, 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:

layout : instance 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_scale: float

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

color : list of color objects | color object | None

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

border : str

matplotlib borders style to be used for each sensor plot.

ylim : dict | None

ylim for plots (after scaling has been applied). The value determines the upper and lower subplot limits. e.g. ylim = dict(eeg=[-20, 20]). Valid keys are eeg, mag, grad, misc. If None, the ylim parameter for each channel is determined by the maximum absolute peak.

scalings : dict | None

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

title : str

Title of the figure.

proj : bool | ‘interactive’

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

vline : list of floats | None

The values at which to show a vertical line.

fig_facecolor : str | obj

The figure face color. Defaults to black.

fig_background : None | numpy ndarray

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

axis_facecolor : str | obj

The face color to be used for each sensor plot. Defaults to black.

font_color : str | obj

The color of text in the colorbar and title. Defaults to white.

merge_grads : bool

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

legend : bool | int | string | 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.

show : bool

Show figure if True.

Returns:

fig : instance of matplotlib.figure.Figure

Images of evoked responses at sensor locations

Notes

New in version 0.10.0.

plot_topomap(times=’auto’, ch_type=None, layout=None, vmin=None, vmax=None, cmap=None, sensors=True, colorbar=True, scale=None, scale_time=1000.0, unit=None, res=64, size=1, cbar_fmt=’%3.1f’, time_format=’%01d ms’, proj=False, show=True, show_names=False, title=None, mask=None, mask_params=None, outlines=’head’, contours=6, image_interp=’bilinear’, average=None, head_pos=None, axes=None)[source]

Plot topographic maps of specific time points of evoked data.

Parameters:

times : float | array of floats | “auto” | “peaks”.

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.

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, then channels are chosen in the order given above.

layout : None | Layout

Layout instance specifying sensor positions (does not need to be specified for Neuromag data). If possible, the correct layout file is inferred from the data; if no appropriate layout file was found, the layout is automatically generated from the sensor locations.

vmin : float | callable | None

The value specifying the lower bound of the color range. If None, and vmax is None, -vmax is used. Else np.min(data). If callable, the output equals vmin(data). Defaults to None.

vmax : float | callable | None

The value specifying the upper bound of the color range. If None, the maximum absolute value is used. If callable, the output equals vmax(data). Defaults to None.

cmap : matplotlib 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 (zoom). The mouse scroll can also be used to adjust the range. Hitting space bar resets the range. Up and down arrows can be used to change the colormap. If None (default), ‘Reds’ is used for all positive data, otherwise defaults to ‘RdBu_r’. If ‘interactive’, translates to (None, True).

Warning

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

sensors : bool | str

Add markers for sensor locations to the plot. Accepts matplotlib plot format string (e.g., ‘r+’ for red plusses). If True, a circle will be used (via .add_artist). Defaults to True.

colorbar : bool

Plot a colorbar.

scale : dict | float | None

Scale the data for plotting. If None, defaults to 1e6 for eeg, 1e13 for grad and 1e15 for mag.

scale_time : float | None

Scale the time labels. Defaults to 1e3 (ms).

unit : dict | str | None

The unit of the channel type used for colorbar label. If scale is None the unit is automatically determined.

res : int

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

size : float

Side length per topomap in inches.

cbar_fmt : str

String format for colorbar values.

time_format : str

String format for topomap values. Defaults to “%01d ms”

proj : bool | ‘interactive’

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

show : bool

Show figure if True.

show_names : bool | callable

If True, show channel names on top of the map. If a callable is passed, 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 significant sensors will be shown.

title : str | None

Title. If None (default), no title is displayed.

mask : ndarray of bool, shape (n_channels, n_times) | None

The channels to be marked as significant at a given time point. Indices set to True will be considered. Defaults to None.

mask_params : dict | None

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

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

outlines : ‘head’ | ‘skirt’ | dict | None

The outlines to be drawn. If ‘head’, the default head scheme will be drawn. If ‘skirt’ the head scheme will be drawn, but sensors are allowed to be plotted outside of the head circle. If dict, each key refers to a tuple of x and y positions, the values in ‘mask_pos’ will serve as image mask, and the ‘autoshrink’ (bool) field will trigger automated shrinking of the positions due to points outside the outline. 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’.

contours : int | False | array of float | None

The number of contour lines to draw. If 0, no contours will be drawn. If an array, the values represent the levels for the contours. The values are in uV for EEG, fT for magnetometers and fT/m for gradiometers. If colorbar=True, the ticks in colorbar correspond to the contour levels.

image_interp : str

The image interpolation to be used. All matplotlib options are accepted.

average : float | None

The time window around a given time to be used for averaging (seconds). For example, 0.01 would translate into window that starts 5 ms before and ends 5 ms after a given time point. Defaults to None, which means no averaging.

head_pos : dict | None

If None (default), the sensors are positioned such that they span the head circle. If dict, can have entries ‘center’ (tuple) and ‘scale’ (tuple) for what the center and scale of the head should be relative to the electrode locations.

axes : instance of Axes | list | None

The axes to plot to. If list, the list must be a list of Axes of the same length as times (unless times is None). If instance of Axes, times must be a float or a list of one float. Defaults to None.

Returns:

fig : instance of matplotlib.figure.Figure

The figure.

plot_white(noise_cov, show=True)[source]

Plot whitened evoked response.

Plots the whitened evoked response and the whitened GFP as described in [R7]. 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. The rank estimation will be printed by the logger for each noise covariance estimator that is passed.

Parameters:

noise_cov : list | instance of Covariance | str

The noise covariance as computed by mne.cov.compute_covariance.

show : bool

Whether to show the figure or not. Defaults to True.

Returns:

fig : instance of matplotlib.figure.Figure

The figure object containing the plot.

Notes

New in version 0.9.0.

References

[R7](1, 2) 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.
proj

Whether or not projections are active.

rename_channels(mapping)[source]

Rename channels.

Parameters:

mapping : dict | 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 (new in version 0.10.0).

Notes

New in version 0.9.0.

resample(sfreq, npad=’auto’, window=’boxcar’)[source]

Resample data.

This function operates in-place.

Parameters:

sfreq : float

New sample rate to use

npad : int | 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).

window : string or tuple

Window to use in resampling. See scipy.signal.resample.

Returns:

evoked : instance of mne.Evoked

The resampled evoked object.

save(fname)[source]

Save dataset to file.

Parameters:

fname : string

Name of the file where to save the data.

Notes

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

savgol_filter(h_freq, copy=False)[source]

Filter the data using Savitzky-Golay polynomial method.

Parameters:

h_freq : float

Approximate high cut-off frequency in Hz. Note that this is not an exact cutoff, since Savitzky-Golay filtering [R8] 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.

copy : bool

If True, a copy of the object, filtered, is returned. If False (default), it operates on the object in place.

Returns:

inst : instance of Epochs or Evoked

The object with the filtering applied.

Notes

For Savitzky-Golay low-pass approximation, see:

New in version 0.9.0.

References

[R8](1, 2) Savitzky, A., Golay, M.J.E. (1964). “Smoothing and Differentiation of Data by Simplified Least Squares Procedures”. Analytical Chemistry 36 (8): 1627-39.

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)[source]

Define the sensor type of channels.

Note: The following sensor types are accepted:
ecg, eeg, emg, eog, exci, ias, misc, resp, seeg, stim, syst, ecog, hbo, hbr
Parameters:

mapping : dict

a dictionary mapping a channel to a sensor type (str) {‘EEG061’: ‘eog’}.

Notes

New in version 0.9.0.

set_eeg_reference(ref_channels=None, verbose=None)[source]

Specify which reference to use for EEG data.

By default, MNE-Python will automatically re-reference the EEG signal to use an average reference (see below). 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 and prevent MNE-Python from automatically adding an average reference.

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

No re-referencing:
If the EEG data is already using the proper reference, set ref_channels=[]. This will prevent MNE-Python from automatically re-referencing the data to an average reference.
Average reference:
A new virtual reference electrode is created by averaging the current EEG signal. Make sure that all bad EEG channels are properly marked and set ref_channels=None.
A single electrode:
Set ref_channels to the name of the channel that will act as the new reference.
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'].
Parameters:

ref_channels : list of str | None

The names of the channels to use to construct the reference. If None (default), an average reference will be added as an SSP projector but not immediately applied to the data. If an empty list is specified, the data is assumed to already have a proper reference and MNE will not attempt any re-referencing of the data. Defaults to an average reference (None).

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more).

Returns:

inst : instance of Raw | Epochs | Evoked

Data with EEG channels re-referenced. For ref_channels=None, an average projector will be added instead of directly subtarcting data.

Notes

  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 other than an average reference, the data must be preloaded.
  4. Re-referencing to an average reference is done with an SSP projector. This allows applying this reference without preloading the data. Be aware that on preloaded data, SSP projectors are not automatically applied. Use the apply_proj() method to apply them.

New in version 0.13.0.

set_montage(montage, verbose=None)[source]

Set EEG sensor configuration and head digitization.

Parameters:

montage : instance of Montage or DigMontage

The montage to use.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more).

Notes

Operates in place.

New in version 0.9.0.

shift_time(tshift, relative=True)[source]

Shift time scale in evoked data.

Parameters:

tshift : float

The amount of time shift to be applied if relative is True else the first time point. When relative is True, positive value of tshift moves the data forward while negative tshift moves it backward.

relative : bool

If true, move the time backwards or forwards by specified amount. Else, set the starting time point to the value of tshift.

Notes

Maximum accuracy of time shift is 1 / evoked.info[‘sfreq’]

time_as_index(times, use_rounding=False)[source]

Convert time to indices.

Parameters:

times : list-like | float | int

List of numbers or a number representing points in time.

use_rounding : boolean

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

Returns:

index : ndarray

Indices corresponding to the times supplied.

to_data_frame(picks=None, index=None, scale_time=1000.0, scalings=None, copy=True, start=None, stop=None)[source]

Export data in tabular structure as a pandas DataFrame.

Columns and indices will depend on the object being converted. Generally this will include as much relevant information as possible for the data type being converted. This makes it easy to convert data for use in packages that utilize dataframes, such as statsmodels or seaborn.

Parameters:

picks : array-like of int | None

If None only MEG and EEG channels are kept otherwise the channels indices in picks are kept.

index : tuple of str | None

Column to be used as index for the data. Valid string options are ‘epoch’, ‘time’ and ‘condition’. If None, all three info columns will be included in the table as categorial data.

scale_time : float

Scaling to be applied to time units.

scalings : dict | None

Scaling to be applied to the channels picked. If None, defaults to scalings=dict(eeg=1e6, grad=1e13, mag=1e15, misc=1.0).

copy : bool

If true, data will be copied. Else data may be modified in place.

start : int | None

If it is a Raw object, this defines a starting index for creating the dataframe from a slice. The times will be interpolated from the index and the sampling rate of the signal.

stop : int | None

If it is a Raw object, this defines a stop index for creating the dataframe from a slice. The times will be interpolated from the index and the sampling rate of the signal.

Returns:

df : instance of pandas.core.DataFrame

A dataframe suitable for usage with other statistical/plotting/analysis packages. Column/Index values will depend on the object type being converted, but should be human-readable.