'MATLAB graph plot - coloring nodes smoothly by centrality

In MATLAB, I have a graph that I'd like to plot with its nodes colored according to measures of their centrality. Here's how I currently plot the graph:

sdc = centrality(G, 'degree');
V = plot(G);
for i=1:size(genes,1)
    highlight(V, [i], 'NodeColor', 'g');
end

Of course, this just turns all the nodes green. What I'd like to do is set the node colors smoothly according to the corresponding value of sdc, so that nodes with low values are more blue, those with middling values are green-yellow, and those with high values are more red. Is there a way to do this?



Solution 1:[1]

First, define a color map or use an existing one. E.g. the one called turbo is very similar to the described one.

In the highlight function, the color of the node can be set by providing an RGB triplet after the 'NodeColor' argument. For example this sets the nodes to red:

highlight(V, [i], 'NodeColor', [1 0 0]);

Let's store the chosen color map in a variable and use a smart way of matrix indexing to create an N×3 sized matrix containing the desired color for each data point in the sdc vector.

cm = turbo;
sdc_colors = cm(round(normalize(sdc, 'range', [1, size(cm, 1)])), :);

The explanation of the second line is the following:

  1. first, the number of colors in the map is returned by the size function
  2. a range from 1 to the aforementioned number is created (e.g. [1,255])
  3. the input data is normalized to cover this dynamic range (normalize)
  4. the normalized values are rounded to integers to become valid index values
  5. the colormap (cm) is indexed with this vector as the first index, and with : as the second parameter, which yields an N×3 matrix filled with the appropriate color values for each data point.

After creating this matrix of desired colors, it can be invoked in the for loop with the appropriate indexing. So the complete code is:

cm = turbo;
sdc_colors = cm(round(normalize(sdc, 'range', [1, size(cm, 1)])), :);

for i=1:size(sdc,1)
    highlight(V, [i], 'NodeColor', sdc_colors(i, :));
end

Solution 2:[2]

You can use the NodeCData property. After creating the graph, use the following code:

figure()
p1 = plot(G,'Layout','force','NodeCData',M);
colormap(turbo(max(M)))
p1.NodeFontSize = 14;
p1.MarkerSize   = 10;

Here, the graph is plotted using the force layout method. M is the centrality measure vector corresponding to each node.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ankit Sahay