color nodes in igraph ggraph r

228 views Asked by At

I'd like to color the nodes of a graph based on an attribute in the original dataframe. But I think I haven't "carried through" that aestetic variable to the graph.

Example here that works:

library(dplyr)
library(igraph)
library(ggraph)

data <-
  tibble(
    from = c("a", "a", "a", "b", "b", "c"),
    to = c(1, 2, 3, 1, 4, 2),
    type = c("X", "Y", "Y", "X", "Y", "X")
  )

graph <-
  graph_from_data_frame(data)

ggraph(graph,
       layout = "fr") +
  geom_node_point() +
  geom_edge_link() 

I'd like something like geom_node_point(aes(color = type)), but haven't made type findable in the graph?

1

There are 1 answers

1
Ben Nutzer On BEST ANSWER

The issue here is that you added the type column as an edge-attribute whereas geom_node_point expects a vertex-attribute (see ?graph_from_data_frame: Additional columns are considered as edge attributes.). Another issue is that type is not consistent for either node column (e.g. a is associated with type X and also Y, the same is true for node 2).

To address the first issue you could add additional vertex information to the vertices argument of the graph_from_data_frame function.

The simplest solution to address both issues is to add the type attribute after creating the graph:

 data <-
  tibble(
    from = c("a", "a", "a", "b", "b", "c"),
    to = c(1, 2, 3, 1, 4, 2)
  )

graph <- graph_from_data_frame(data)
V(graph)$type <- bipartite.mapping(graph)$type

The bipartite.mapping function adds either TRUE or FALSE consistently to each vertex of different type.