我有一个数据框d
:
d<-structure(list(V1 = c(1L, 3L, 3L, 2L, 1L, 1L, 7L, 9L, 10L, 9L, 7L), V2 = c(2L, 4L, 5L, 5L, 4L, 6L, 8L, 3L, 1L, 8L, 5L)),
.Names = c("V1", "V2"), class ="data.frame", row.names = c(NA, -11L))
g<-graph.data.frame(d,directed = F)
我会根据数据帧 m
中给出的从属变量为每个顶点分配一种或多种颜色
m<-structure(list(vertex = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 9L, 9L, 10L, 1L, 1L, 6L, 6L), affilation = c(1L, 1L, 1L, 2L, 2L, 1L, 3L, 3L, 3L, 2L, 2L, 3L, 3L, 2L, 2L, 3L)),
.Names = c("vertex", "affilation"), class = "data.frame", row.names = c(NA, -16L))
我想问一下igraph包中是否有一个简单的方法可以根据其从属关系为每个顶点分配一种或多种颜色
最佳答案
(编辑)因为边被指定为整数,所以图中的顶点没有按顺序排列。我更改了初始 graph.data.frame 调用以指定顺序,然后一切正常。
g<-graph.data.frame(d,directed = F, vertices = 1:10)
您可以通过将颜色分配给 V(g)$color 来将颜色分配为顶点属性。这是您的示例的一些代码(仅适用于单个从属关系)
# Put in vertex order
m <- m[order(m$vertex), ]
# Create a palette (any palette would do)
pal <- rainbow(n=length(unique(m$affilation)))
# Get each node's first affiliation
oneAffil <- m$affilation[!duplicated(m$vertex)]
# Assign to the vertices as a color attribute
V(g)$color <- pal[oneAffil]
plot(g)
现在,对于多个从属关系,您想要什么并不太清楚。您可以查看 vertex.shape.pie
,它可以绘制具有多种颜色的形状。像这样的东西对我有用(但有相当多的数据争论才能让它继续)
# Use a cast to split out affiliation in each group as a column
library(reshape2)
am <- acast(m, formula = vertex ~ affilation)
# Turn this into a list
values <- lapply(seq_len(nrow(am)), function(i) am[i,])
plot(g, vertex.shape="pie", vertex.pie=values, vertex.pie.color=list(pal))
关于r - 为 igraph 中的每个顶点分配多种颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33874935/