I have a network in iGraph
that has multiple vertex attributes that represent various factors. I want to color the vertices when I plot the graph based on a specific attribute. Similar to how you use color = variable
in ggplot
.
The parameter vertex.color
within plot()
can be used to set the vertex color for all vertices within the network or it can accept RGB values and set vertex color for each vertex.
I've seen RColorBrewer
as a way to create a pallet, but I'm not sure how to map that back to the vertex attributes. I also don't want to hard code the colors for each attribute value, as I have multiple attributes, each with a different number of levels.
library(igraph)
library(RColorBrewer)
# create an example network
g <- make_ring(5)
# assign vertex attributes
g <- set.vertex.attribute(g, 'group', 1, 'A')
g <- set.vertex.attribute(g, 'group', 2, 'A')
g <- set.vertex.attribute(g, 'group', 3, 'B')
g <- set.vertex.attribute(g, 'group', 4, 'B')
g <- set.vertex.attribute(g, 'group', 5, 'C')
# create color pallet based on unique values for vertex attribute
pal <- brewer_pal(length(unique(V(g)$group)), "Dark2")
# plot network
plot(g, vertex.color = "gray")
Typo? At least in my version of RColorBrewer it is brewer.pal
not brewer_pal
We want to use the value of the group
attribute to select a color from the palette that you generated, but those values are strings, not numbers. One way to get by this is to convert the strings to factors and then use those as numbers. That will convert each unique string value to a unique numeric value. We can use that to select the color.
plot(g, vertex.color = pal[as.numeric(as.factor(vertex_attr(g, "group")))])