Reputation: 13
I am trying to create a plot in igraph in which nodes are colored red for females and blue for males. I have a data frame called "advisory_edge_1" that houses my edge list. I have another data frame called "gender_attributes" which includes a list of nodes in the first column and a gender indicator in the second column (1=female, 2=male). When I set my vertex colors I get the error "Warning message:In length(vattrs[[name]]) <- vc : length of NULL cannot be changed".
I am unsure why I am getting this message. My code is below.
g2 <- graph_from_data_frame(d=advisory_edge_1, vertices = gender_attributes, directed = FALSE)
V(g2)$color <- ifelse(V(g2)$gender == 1, "red", "blue")
plot(g2, layout=layout.circle(g2))
Upvotes: 1
Views: 338
Reputation: 18704
FYI It's a good idea to make your questions reproducible. Your method didn't work because V(g2)
only contains the literal nodes. None of the other elements of the data frame are in that object. Here are two different ways you could do this (adapted for the data I used since I don't have your data).
First, the data I used (completely stole from an igraph
example).
# data from examples @ igraph
actors <- data.frame(name=c("Alice", "Bob", "Cecil", "David","Esmeralda"),
age=c(48, 33, 45, 34, 21),
gender=c("F","M","F","M","F"))
relations <- data.frame(from=c("Bob", "Cecil", "Cecil", "David",
"David", "Esmeralda"),
to=c("Alice", "Bob", "Alice", "Alice", "Bob", "Alice"),
same.dept=c(FALSE, FALSE, TRUE, FALSE, FALSE, TRUE),
friendship=c(4, 5, 5, 2, 1, 1),
advice=c(4, 5, 5, 4, 2, 3))
Here's a slight adaptation to the method you coded your graph colors.
g2 <- graph_from_data_frame(relations, directed = F, vertices = actors)
V(g2)$color <- ifelse(actors$gender == "M",
"red", "blue")
plot(g2, layout = layout.circle(g2), vertex.label.dist = 2)
Here's another way you could do this.
g <- graph_from_data_frame(relations, directed = F, vertices = actors)
plot(g, vertex.label.dist = 2, vertex.size = 10,
vertex.color = ifelse(actors$gender == "M",
"red", "blue"))
Upvotes: 1