Reputation: 387
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!
Upvotes: 2
Views: 1030
Reputation: 2435
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")
Upvotes: 2