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?
The issue here is that you added the
type
column as an edge-attribute whereasgeom_node_point
expects a vertex-attribute (see?graph_from_data_frame
: Additional columns are considered as edge attributes.). Another issue is thattype
is not consistent for either node column (e.g.a
is associated with typeX
and alsoY
, the same is true for node2
).To address the first issue you could add additional vertex information to the
vertices
argument of thegraph_from_data_frame
function.The simplest solution to address both issues is to add the type attribute after creating the graph:
The
bipartite.mapping
function adds eitherTRUE
orFALSE
consistently to each vertex of different type.