Python launcher opens and immediately closes matplotlib.

  • MNE version: e.g. 0.24.0
  • operating system: e.g. macOS 12

Here is the following code I am using


# This script uses MNE to analyze and visualize neural time series data

import mne 
import numpy as np
import os
import matplotlib as plt


# Set the folder path
folder_path = '/path_to_file/'

# create an empty list to store the raw data
raw_data = []

# loop through the files in the folder
for filename in os.listdir(folder_path):
    # check if the file is a BrainVision file
    if filename.endswith(".vhdr"):
        # construct the full file path
        file_path = os.path.join(folder_path, filename)
        # load the data from the BrainVision file
        raw = mne.io.read_raw_brainvision(file_path)
        # add the raw data to the list
        raw_data.append(raw)

# combine the raw data into a single raw object
raw = mne.concatenate_raws(raw_data)

print(raw.info)

raw.plot_psd(fmax=50)
raw.plot(duration=5, n_channels=31)

Python launcher will open matplotlib but immediately close it. I am not sure what the problem could be. Could it be an issue with MNE dependancies?

Hello and welcome to the forum!

I believe the following posting answers your question:

Best wishes,
Richard

The answer @richard linked to may be a bit confusing since it’s not clear that you’re using PyCharm (as that asker was). The gist of the answer is the same though: Python can run in two ways: interactive and non-interactive mode. From the command line, this is controlled by the -i flag:

$ python myscript.py     # non-interactive
$ python -i myscript.py  # interactive

in interactive mode, when the end of the script is reached, the python interpreter stays open and lets you enter additional commands. A side-effect of this is that any plots that your script opened will also stay open.

If you’re running your script through an IDE, it might automatically use interactive mode, or you may need to look around in the commands / settings for a way to tell it which mode to use when running scripts.

As mentioned in the linked answer, another option is using the MNE-Python plotting function option block=True, which pauses script execution while that plot is open, and continues with the script only after you manually close the plot. However, not all plotting functions have this option (raw.plot_psd() does not; raw.plot() does) so it won’t always be enough.