assign multiple color to each vertex in igraph

元气小坏坏 提交于 2020-01-13 05:36:18

问题


I have a dataframe 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)

I would assign to each vertex one or more colors depending on its affiliation variable given in a dataframe 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))

i would to ask if there is a simple method in igraph package to assign one or multiple color to each vertex according to its affiliation


回答1:


(EDIT) Because the edges were specified as integers the vertices were not in order in the graph. I changed the initial graph.data.frame call to specify the order, then everything should work.

g<-graph.data.frame(d,directed = F, vertices = 1:10)

You can assign color as a vertex attribute by assigning into V(g)$color. Here's some code for your example (only for a single affiliation)

# 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)

Now for multiple affiliations it's not too clear what you want. You could look at vertex.shape.pie that can draw shapes with more than one color on. Something like this works for me (but there's quite a bit of data wrangling to get it going)

# 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))



来源:https://stackoverflow.com/questions/33874935/assign-multiple-color-to-each-vertex-in-igraph

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!