Plot 3D nifiti on surface using nilearn

Hi everyone,

I have a 3D nifty file (brain map) that I would like to plot on a surface.

I am using the following code however, texture variable contains NaNs and the plotting function fails.

Any tip how to overcome this?


import numpy as np, os, sys
from nilearn import plotting, datasets; from nilearn.surface import load_surf_data
import numpy as np, os, warnings, matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
from matplotlib import ticker
from mpl_toolkits.mplot3d import Axes3D
from nilearn import surface

hemisphere = 'left'
view = 'medial'
black_bg = True
colorbar= True
cmap = 'hsv'

# Load the surface 
fsaverage = datasets.fetch_surf_fsaverage('fsaverage')

# The stat map
stat_img = '/Users/loukas/Desktop/stat_map.nii'

# The texture
texture = surface.vol_to_surf(stat_img, fsaverage.pial_left)

fig = plt.figure(dpi=300)
ax = fig.add_subplot(111, projection='3d')
# Plotting
plotting.plot_surf_roi(fsaverage["infl_{}".format(hemisphere)], roi_map = texture, \
	hemi = hemisphere, view = view, bg_map = fsaverage["sulc_{}".format(hemisphere)], \
	bg_on_data = True, darkness = 0.6, output_file = 'mapped_signal.png', \
	cmap = cmap, colorbar = colorbar, black_bg=black_bg, axes= ax, figure=fig, )
#for ax in plt.gcf().axes:
#	ax.yaxis.set_major_formatter(ticker.FormatStrFormatter(">%.4f<"))

Data: - Upload files for free and transfer big files easily.
Pass: makis

A quick and dirty fix is to smooth slightly (e.g. fwhm=1mm) prior to projection. Internally, the code replaces NaNs with 0’s.
There is proabbly a better way to do that, though…
My 2c,

Hi @makaros622

I had a look at this today, and it turns out plot_surf_stat_map can handle textures with nans while plot_surf_roi cannot…
I don’t see a good reason for this, so I opened the following PR to fix the issue: handle nans in plot_surf_roi by NicolasGensollen · Pull Request #2743 · nilearn/nilearn · GitHub

Hope this helps!

Great. Thanks. It is indeed strange that only the first function can handle nans