How to keep plotting window open in MNE with Python?

1.2k views Asked by At

In MNE with Python, I would like to keep the interactive plotting window open once the calling def is executed completely.

However, this is not achievable via the following code:

def get_plot():
    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)
    raw.plot()

get_plot()

Such that, once the get_plot() is completed, the plot window is automatically closed.

Also, I am on Windows 10 with PyCharm 2020.1.3.

May I know how to handle this issue?

1

There are 1 answers

0
rpb On BEST ANSWER

To get the interactive plot in PyCharm. The Show plots in tool window first need to be disabled.

Disable Settings | Tools | Python Scientific | Show plots in tool window

Then, matplotlib.use('TkAgg') should allowed to create an interactive plot window.

MNE plot() is based on matplotlib. See the source file plot_raw. Based from the OP, matplotlib equip with block parameter you can pass to plt.show(). This allow the plot to be open even after the function is successfully invoke.

Apparently, mne group have include this parameter as well.

So, the above objective can be achieved simply by setting plot(block=True)

Then, the full code is

import mne
import matplotlib
matplotlib.use('TkAgg')

def get_plot():
    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)
    raw.plot(block=True)

get_plot()