<jupyter_start><jupyter_text>Visualizing epoched data========================This tutorial shows how to plot epoched data as time series, how to plot thespectral density of epoched data, how to plot epochs as an imagemap, and how toplot the sensor locations and projectors stored in :class:`~mne.Epochs`objects.   :depth: 2We'll start by importing the modules we need, loading the continuous (raw)sample data, and cropping it to save memory:<jupyter_code>import os
import mne

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False).crop(tmax=120)<jupyter_output><empty_output><jupyter_text>To create the :class:`~mne.Epochs` data structure, we'll extract the eventIDs stored in the :term:`stim channel`, map those integer event IDs to moredescriptive condition labels using an event dictionary, and pass those to the:class:`~mne.Epochs` constructor, along with the :class:`~mne.io.Raw` dataand the desired temporal limits of our epochs, ``tmin`` and ``tmax`` (for adetailed explanation of these steps, see `tut-epochs-class`).<jupyter_code>events = mne.find_events(raw, stim_channel='STI 014')
event_dict = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
              'visual/right': 4, 'face': 5, 'buttonpress': 32}
epochs = mne.Epochs(raw, events, tmin=-0.2, tmax=0.5, event_id=event_dict,
                    preload=True)
del raw<jupyter_output><empty_output><jupyter_text>Plotting ``Epochs`` as time series^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.. sidebar:: Interactivity in pipelines and scripts    To use the interactive features of the :meth:`~mne.Epochs.plot` method    when running your code non-interactively, pass the ``block=True``    parameter, which halts the Python interpreter until the figure window is    closed. That way, any channels or epochs that you mark as "bad" will be    taken into account in subsequent processing steps.To visualize epoched data as time series (one time series per channel), the:meth:`mne.Epochs.plot` method is available. It creates an interactive windowwhere you can scroll through epochs and channels, enable/disable anyunapplied :term:`SSP projectors ` to see how they affect thesignal, and even manually mark bad channels (by clicking the channel name) orbad epochs (by clicking the data) for later dropping. Channels marked "bad"will be shown in light grey color and will be added to``epochs.info['bads']``; epochs marked as bad will be indicated as ``'USER'``in ``epochs.drop_log``.Here we'll plot only the "catch" trials from the `sample dataset`, and pass in our events array so that the button pressresponses also get marked (we'll plot them in red, and plot the "face" eventsdefining time zero for each epoch in blue). We also need to pass inour ``event_dict`` so that the :meth:`~mne.Epochs.plot` method will know whatwe mean by "buttonpress" — this is because subsetting the conditions bycalling ``epochs['face']`` automatically purges the dropped entries from``epochs.event_id``:<jupyter_code>catch_trials_and_buttonpresses = mne.pick_events(events, include=[5, 32])
epochs['face'].plot(events=catch_trials_and_buttonpresses, event_id=event_dict,
                    event_colors=dict(buttonpress='red', face='blue'))<jupyter_output><empty_output><jupyter_text>Plotting projectors from an ``Epochs`` object^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^In the plot above we can see heartbeat artifacts in the magnetometerchannels, so before we continue let's load ECG projectors from disk and applythem to the data:<jupyter_code>ecg_proj_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                             'sample_audvis_ecg-proj.fif')
ecg_projs = mne.read_proj(ecg_proj_file)
epochs.add_proj(ecg_projs)
epochs.apply_proj()<jupyter_output><empty_output><jupyter_text>Just as we saw in the `tut-section-raw-plot-proj` section, we can plotthe projectors present in an :class:`~mne.Epochs` object using the same:meth:`~mne.Epochs.plot_projs_topomap` method. Since the original threeempty-room magnetometer projectors were inherited from the:class:`~mne.io.Raw` file, and we added two ECG projectors for each sensortype, we should see nine projector topomaps:<jupyter_code>epochs.plot_projs_topomap(vlim='joint')<jupyter_output><empty_output><jupyter_text>Note that these field maps illustrate aspects of the signal that *havealready been removed* (because projectors in :class:`~mne.io.Raw` data areapplied by default when epoching, and because we called:meth:`~mne.Epochs.apply_proj` after adding additional ECG projectors fromfile). You can check this by examining the ``'active'`` field of theprojectors:<jupyter_code>print(all(proj['active'] for proj in epochs.info['projs']))<jupyter_output><empty_output><jupyter_text>Plotting sensor locations^^^^^^^^^^^^^^^^^^^^^^^^^Just like :class:`~mne.io.Raw` objects, :class:`~mne.Epochs` objectskeep track of sensor locations, which can be visualized with the:meth:`~mne.Epochs.plot_sensors` method:<jupyter_code>epochs.plot_sensors(kind='3d', ch_type='all')
epochs.plot_sensors(kind='topomap', ch_type='all')<jupyter_output><empty_output><jupyter_text>Plotting the power spectrum of ``Epochs``^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Again, just like :class:`~mne.io.Raw` objects, :class:`~mne.Epochs` objectshave a :meth:`~mne.Epochs.plot_psd` method for plotting the `spectraldensity`_ of the data.<jupyter_code>epochs['auditory'].plot_psd(picks='eeg')<jupyter_output><empty_output><jupyter_text>Plotting ``Epochs`` as an image map^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^A convenient way to visualize many epochs simultaneously is to plot them asan image map, with each row of pixels in the image representing a singleepoch, the horizontal axis representing time, and each pixel's colorrepresenting the signal value at that time sample for that epoch. Of course,this requires either a separate image map for each channel, or some way ofcombining information across channels. The latter is possible using the:meth:`~mne.Epochs.plot_image` method; the former can be achieved with the:meth:`~mne.Epochs.plot_image` method (one channel at a time) or with the:meth:`~mne.Epochs.plot_topo_image` method (all sensors at once).By default, the image map generated by :meth:`~mne.Epochs.plot_image` will beaccompanied by a scalebar indicating the range of the colormap, and a timeseries showing the average signal across epochs and a bootstrapped 95%confidence band around the mean. :meth:`~mne.Epochs.plot_image` is a highlycustomizable method with many parameters, including customization of theauxiliary colorbar and averaged time series subplots. See the docstrings of:meth:`~mne.Epochs.plot_image` and `mne.viz.plot_compare_evokeds` (which isused to plot the average time series) for full details. Here we'll show themean across magnetometers for all epochs with an auditory stimulus:<jupyter_code>epochs['auditory'].plot_image(picks='mag', combine='mean')<jupyter_output><empty_output><jupyter_text>To plot image maps for individual sensors or a small group of sensors, usethe ``picks`` parameter. Passing ``combine=None`` (the default) will yieldseparate plots for each sensor in ``picks``; passing ``combine='gfp'`` willplot the global field power (useful for combining sensors that respond withopposite polarity).<jupyter_code>epochs['auditory'].plot_image(picks=['MEG 0242', 'MEG 0243'])
epochs['auditory'].plot_image(picks=['MEG 0242', 'MEG 0243'], combine='gfp')<jupyter_output><empty_output><jupyter_text>To plot an image map for *all* sensors, use:meth:`~mne.Epochs.plot_topo_image`, which is optimized for plotting a largenumber of image maps simultaneously, and (in interactive sessions) allows youto click on each small image map to pop open a separate figure with thefull-sized image plot (as if you had called :meth:`~mne.Epochs.plot_image` onjust that sensor). At the small scale shown in this tutorial it's hard to seemuch useful detail in these plots; it's often best when plottinginteractively to maximize the topo image plots to fullscreen. The default isa figure with black background, so here we specify a white background andblack foreground text. By default :meth:`~mne.Epochs.plot_topo_image` willshow magnetometers and gradiometers on the same plot (and hence not show acolorbar, since the sensors are on different scales) so we'll also pass a:class:`~mne.channels.Layout` restricting each plot to one channel type.First, however, we'll also drop any epochs that have unusually high signallevels, because they can cause the colormap limits to be too extreme andtherefore mask smaller signal fluctuations of interest.<jupyter_code>reject_criteria = dict(mag=3000e-15,     # 3000 fT
                       grad=3000e-13,    # 3000 fT/cm
                       eeg=150e-6)       # 150 µV
epochs.drop_bad(reject=reject_criteria)

for ch_type, title in dict(mag='Magnetometers', grad='Gradiometers').items():
    layout = mne.channels.find_layout(epochs.info, ch_type=ch_type)
    epochs['auditory/left'].plot_topo_image(layout=layout, fig_facecolor='w',
                                            font_color='k', title=title)<jupyter_output><empty_output><jupyter_text>To plot image maps for all EEG sensors, pass an EEG layout as the ``layout``parameter of :meth:`~mne.Epochs.plot_topo_image`. Note also here the use ofthe ``sigma`` parameter, which smooths each image map along the verticaldimension (across epochs) which can make it easier to see patterns across thesmall image maps (by smearing noisy epochs onto their neighbors, whilereinforcing parts of the image where adjacent epochs are similar). However,``sigma`` can also disguise epochs that have persistent extreme values andmaybe should have been excluded, so it should be used with caution.<jupyter_code>layout = mne.channels.find_layout(epochs.info, ch_type='eeg')
epochs['auditory/left'].plot_topo_image(layout=layout, fig_facecolor='w',
                                        font_color='k', sigma=1)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10999309460392621, 'fraction_numerical': 0.006708099043109401, 'mean_word_length': 5.736212624584717, 'pattern_counts': {'":': 0, '<': 49, '<?xml version=': 0, '>': 49, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '12', 'dir': 'jupyter-structured-clean-dedup', 'id': '655297', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 3116, 'n_tokens_neox': 2953, 'n_words': 1053, 'path': 'jumeg/epocher/plot_20_visualize_epochs.ipynb', 'repo_name': 'fboers/jumeg', 'size': '10137'}