简体   繁体   中英

Is there an easy way to color network nodes by degree in igraph for R?

Using the igraph package for R, I would like to color the nodes of a network by their degrees. The colors should represent a gradient, for instance from blue to red, or from yellow to red, from the lowest to the highest degree observed in the network.

I've found a working solution here using the functions setNames and colorRampPalette .

Nevertheless, isn't there another solution, using R palettes, like heat.colors or brewer.pal ?

Let me give you an example, simulating the kind of network I'm analyzing:

g <- sample_bipartite(8, 20, type = "gnm", m = 29)

degrees <- degree(g)

colors <- heat.colors(length(unique(degrees)))

plot(g,
     vertex.color = colors)

You see? The color gradient doesn't match the degree gradient.

How can the order of the colors match the order of the degrees, from lowest to highest?

Thank you very much!

I am not sure this is the best way to do this, especially for the case in which you have many values, or continuous centrality if the network is weighted. In that case, it would be better to have intervals.

However, if your data is similar to the one in your example, this might help:

library(igraph)
g <- sample_bipartite(8, 20, type = "gnm", m = 29)

V(g)$degree <- degree(g)

#' maybe it s better to have a full sequence, instead of the unique values,
#' in case you have large gaps in between the unique degree values?
#' If not, can use unique values, as in your example
uni_all <- seq( min(V(g)$degree), max(V(g)$degree))

colors <- data.frame( color = heat.colors(length(uni_all), rev = T),
                      levels = uni_all)
  
# Use match to get the index of right color, matching on levels
V(g)$color <- colors$color[match(V(g)$degree, colors$levels)]

# use degree as labels
V(g)$label <- V(g)$degree


plot(g)

在此处输入图像描述

In case you want to check which colors have been assigned to which nodes:

k <- as_data_frame(g, what = "vertices")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM