Extracting colorbar from `nilearn.plotting.plot_stat_map` figure

Hi all,

Does anyone know of a way to extract the colorbar from a display output object generated using the nilearn.plotting.plot_stat_map() function? Or even just recreate the same colorbar from a given stat image?

Thanks!
Shawn

This snippet is used to save the colormap in an image file:

It will reproduce exactly what’s shown with nilearn.plotting.view_img and I suspect it should also work for nilearn.plotting.plot_stat_map although you may want to test it.

2 Likes

Amazing, thanks!

This pointed me in the right direction. I ended up using the functions in nilearn.plotting.html_stat_map to recreate the colorbar of stat map like this:

import nibabel as nib
from nilearn.plotting.html_stat_map import _mask_stat_map, colorscale
from nilearn.plotting import cm

im_file = 'stats.nii.gz'
nib_img = nib.load(im_file)

mask_img, stat_map_img, data, threshold = _mask_stat_map(nib_img, 1e-6)
        
colors = colorscale(cm.cold_hot, data.ravel(), threshold=threshold,
                        symmetric_cmap=True, vmax=None,vmin=None)

And now I can add the colorbar anywhere in a figure using:

from matplotlib import cm as mpl_cm
fig.colorbar(mpl_cm.ScalarMappable(norm=colors['norm'], cmap=colors['cmap']), **)

My workaround is probably not the most elegant approach, but my dilemma is solved for now! :smile:
(Also open to any other tips!)

1 Like