r - 为 igraph 中的每个顶点分配多种颜色

标签 r igraph

我有一个数据框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)

enter image description here

现在,对于多个从属关系,您想要什么并不太清楚。您可以查看 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))

enter image description here

关于r - 为 igraph 中的每个顶点分配多种颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33874935/

相关文章:

R 创建函数添加水年列

R-genalg 包 : Get Fittest From Past Generation

R 取消列出分组数据框

igraph - igraph 1.0 中的 community.to.membership

c++ - 在 C/++ 上的只读共享内存中具有输入图的图算法 (lib)

R:从图中减去子图

r - 具有嵌套变量的 lme 中的多个随机斜率和多个随机截距

r - 在 R 中使用墨卡托投影向 map 添加点

r - 使用 tidyverse 从选择性 "Per Day"数字创建 "Per Month"行

r - 如何在 igraph R 中创建自循环?