使用 igraph 和 vertex.pie 的彩色节点

Multicolored nodes using igraph and vertex.pie

我想创建多色节点。我想留在 igraph。我已经找到 vertex.shape.pie 选项。

这是一些示例数据:

test_fun <- function(color1,color2,len){
  vec <- replicate(len,sample(c(color1,color2,NA),1))
  return(vec)
}

set.seed(50)
num_nodes<- 20
test_graph <- erdos.renyi.game(num_nodes, 1/6)
V(test_graph)$color_1 <- test_fun("darkgreen","blue",num_nodes)
V(test_graph)$color_2 <- test_fun("brown","blueviolet",num_nodes)
V(test_graph)$color_3 <- test_fun("red","green",num_nodes)
V(test_graph)$color_4 <- test_fun("red","green",num_nodes)
plot(test_graph, vertex.size=7)


>test_graph
IGRAPH U--- 20 28 -- Erdos renyi (gnp) graph
+ attr: name (g/c), type (g/c), loops (g/l), p (g/n), color_1 (v/c), color_2 (v/c), color_3 (v/c), color_4 (v/c)

如您所见,我在使用 test_fun 时引入了 NAs。这是故意模仿我的数据。

我现在希望使用 vertex.shape.pie 选项将顶点设为饼图。每个节点应根据 color_1、color_2、color_3 和 color_4 中的属性颜色进行着色。 如果节点的列没有 NA,则分配 4 种颜色, 如果节点的一列是 NA,则分配 3 种颜色, 等等。

感谢您的帮助!

PS.:

这是来自 http://igraph.org/r/doc/vertex.shape.pie.html

的 igraph 示例
g <- graph.ring(10)
values <- lapply(1:10, function(x) sample(1:10,3))
if (interactive()) {
  plot(g, vertex.shape="pie", vertex.pie=values,
       vertex.pie.color=list(heat.colors(5)),
       vertex.size=seq(10,30,length=10), vertex.label=NA)
}

但我无法在我的示例中应用它

编辑 将种子更改为 50

vertex.pie 需要一个包含 values/proportions 的列表,每种颜色都将包含在饼图中。 您需要将 color_* 变量转换为该变量。

为此,您可以先将它们绑定在一起:

v<-cbind(V(test_graph)$color_1,V(test_graph)$color_2,V(test_graph)$color_3,V(test_graph)$color_4)

然后为每个顶点创建一个包含 6 个值(每种颜色一个)的向量,其中包含 0 和 1,如果节点具有该颜色则为 1,否则为 0。

colors<-c("darkgreen","blue","blueviolet","brown","red","green")
values<-apply(v,1,function(x){
  sapply(colors,function(y){ifelse(y %in% x,1,0)})
})
values<-as.list(as.data.frame(values)) 

然后您可以使用您提到的函数进行绘图:

plot(test_graph, vertex.shape="pie", vertex.pie=values,
    vertex.pie.color=list(colors),
    vertex.size=seq(10,30,length=10))

我将 set.seed 更改为 50,因为 42 个顶点仅获得 NAs,因此无法绘制它们...

总代码为:

library(igraph)

test_fun <- function(color1,color2,len){
  vec <- replicate(len,sample(c(color1,color2,NA),1))
  return(vec)
}

set.seed(50)
num_nodes<- 20
test_graph <- erdos.renyi.game(num_nodes, 1/6)
V(test_graph)$color_1 <- test_fun("darkgreen","blue",num_nodes)
V(test_graph)$color_2 <- test_fun("brown","blueviolet",num_nodes)
V(test_graph)$color_3 <- test_fun("red","green",num_nodes)
V(test_graph)$color_4 <- test_fun("red","green",num_nodes)

colors<-c("darkgreen","blue","blueviolet","brown","red","green")

v<-cbind(V(test_graph)$color_1,V(test_graph)$color_2,V(test_graph)$color_3,V(test_graph)$color_4)
values<-apply(v,1,function(x){
  sapply(colors,function(y){ifelse(y %in% x,1,0)})
})
values<-as.list(as.data.frame(values)) 

plot(test_graph, vertex.shape="pie", vertex.pie=values,
     vertex.pie.color=list(colors),
     vertex.size=seq(10,30,length=10))