[nilearn] Legend in plot_connectome

nilearn

#1

Hi,

I’m using plotting.plot_connectome to plot my nodes and their correlations. I’m using the node_color attribute to pass a list of different colours according to the lobe each node is in.

How can I put a legend in the figure stating which is the label of each colour?

I have been trying to play with node_kwargs to pass the labels, but so far I was unsuccessful. Can you help me on this?


#2

AFAIK. I can tell you that getting legend is not straight forward. You may need to write some code for this.
I can try few options and tell you if it worked or not.


#3

I think that the best approach is to craft a legend from scratch. The following stackoverflow answer will tell you how to do it:

The important thing to keep in mind is that all of nilearn plotting is using matplotlib, and hence all kind of crazy things are possible by adding a layer of matplotlib to it.


#4

Kind of hacky version.

What you could do is:

plot connectome as usual with nodes and matrix but in a display, like this

 display = plotting.plot_connectome(......)

Use for loop over the number of coords. Use the same colormap, marker size, etc in below
for loop. Default colormap for plot connectome is shown below in the code and marker size.

marker_coords = np.asarray(node_coords)
node_color = matplotlib.cm.Set2(np.linspace(0, 1, len(marker_coords)))
# labels should be the names of each node
for i in range(len(marker_coords)):
     display.add_markers(marker_coords=[marker_coords[i]], marker_color=node_color[i], marker_size=50,
     label=labels[i])
plt.legend()

You need to adjust legend arguments: ncol, loc, etc to make it look pretty.

I would not recommend this way because it would the code complicated. But, it should work.
HTH


#5

@KamalakerD Thanks for the tip. I was trying to make your code work, but I’m getting TypeErrors. I’m putting a screenshot here. I wasn’t able to figure out what the problem is, as I’m using the same variables as before.
Do you have any working code with your solution?


#6

That was a bug. Fixed now in master.
Please have a look at this PR https://github.com/nilearn/nilearn/pull/1597


#7

Oh, I see, although it’s in the master it’s not released yet? I guess that’s why I have the previous code. Thanks.