有没有一种简单的方法可以在 igraph for R 中按度为网络节点着色?

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

使用 R 的 igraph 包,我想根据度数为网络的节点着色。颜色应表示渐变,例如从蓝色到红色,或从黄色到红色,从网络中观察到的最低程度到最高程度。

我在这里找到 a working solution 使用函数 setNamescolorRampPalette

然而,难道没有另一种解决方案,使用 R 调色板,如 heat.colorsbrewer.pal

让我举个例子,模拟我正在分析的那种网络:

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

degrees <- degree(g)

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

plot(g,
     vertex.color = colors)

看到了吗?颜色渐变与度数渐变不匹配

颜色的顺序如何匹配度数的顺序,从低到高?

非常感谢!

我不确定这是执行此操作的最佳方法,特别是对于您有很多值的情况,或者如果网络是加权的则连续中心性的情况。那样的话,还是有间隔比较好。

但是,如果您的数据与示例中的数据相似,这可能会有所帮助:

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)

如果您想检查哪些颜色已分配给哪些节点:

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