简体   繁体   English

是否有一种简单的方法可以在 R 的 igraph 中按度数对网络节点进行着色?

[英]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.使用用于 R 的igraph package,我想按其度数为网络的节点着色。 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. colors 应该表示从网络中观察到的最低程度到最高程度的梯度,例如从蓝色到红色,或从黄色到红色。

I've found a working solution here using the functions setNames and colorRampPalette .我在这里使用函数setNamescolorRampPalette找到了一个可行的解决方案

Nevertheless, isn't there another solution, using R palettes, like heat.colors or brewer.pal ?尽管如此,是否还有其他解决方案,使用 R 调色板,如heat.colorsbrewer.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? colors 的顺序如何匹配度数从低到高的顺序?

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:如果您想检查哪些 colors 已分配给哪些节点:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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