How to save plot_sensors_connectivity()?

plot_sensors_connectivity() returns a 3D scene, so saving it to disk is a little bit more complicated. Here’s a fully reproducible working example:

# %%

import mne
from mne_connectivity import spectral_connectivity_epochs
from mne.datasets import sample
from mne_connectivity.viz import plot_sensors_connectivity
import matplotlib.pyplot as plt

data_path = sample.data_path()
raw_fname = data_path / 'MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path / 'MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'

raw = mne.io.read_raw_fif(raw_fname)
raw.info['bads'] += ['MEG 2443']
picks = mne.pick_types(raw.info, meg='grad', eeg=False, stim=False, eog=True,
                       exclude='bads')

events = mne.read_events(event_fname)
event_id, tmin, tmax = 3, -0.2, 1.5  # need a long enough epoch for 5 cycles
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6))

fmin, fmax = 4., 9.
sfreq = raw.info['sfreq']  # the sampling frequency
tmin = 0.0  # exclude the baseline period
epochs.load_data().pick_types(meg='grad')  # just keep MEG and no EOG now
con = spectral_connectivity_epochs(
    epochs, method='pli', mode='multitaper', sfreq=sfreq, fmin=fmin, fmax=fmax,
    faverage=True, tmin=tmin, mt_adaptive=False, n_jobs=1
)

# %%
# Do the actual plotting
connectivity_fig = plot_sensors_connectivity(
    epochs.info,
    con.get_data(output='dense')[:, :, 0]
)
# Take a screenshot of the 3D scene
screenshot = connectivity_fig.plotter.screenshot()

# The screenshot is just a NumPy array, so we can display it via imshow()
# and then save it to a file.
fig, ax = plt.subplots(figsize=(10, 10))
ax.imshow(screenshot, origin='upper')
ax.set_axis_off()  # Disable axis labels and ticks
fig.tight_layout()
fig.savefig('connectivity.png', dpi=150)

5 Likes