Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign multiple color to each vertex in igraph

Tags:

r

igraph

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

like image 332
Camilla Avatar asked Sep 16 '25 08:09

Camilla


1 Answers

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

enter image description here

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

enter image description here

like image 151
dougmet Avatar answered Sep 17 '25 22:09

dougmet