Phil Phil - 22 days ago 7
R Question

Retrieving node coordinates from ggraph network chart

Let's say I produce this chart:

library(ggraph)
library(igraph)

my_chart <- graph_from_data_frame(highschool)
set.seed(2017)

ggraph(my_chart, layout = "nicely") + geom_edge_link() + geom_node_point()


enter image description here

How would one retrieve the x and y coordinates of the nodes from this chart?

Answer Source

Using ggplot_build

library(ggraph)
library(igraph)

my_chart <- graph_from_data_frame(highschool)
set.seed(2017)

p <- ggraph(my_chart, layout = "nicely") + geom_edge_link() + geom_node_point()

pg <- ggplot_build(p)

lines are in pg[[1]][[1]]

ggplot(data= pg[[1]][[1]])+
  geom_line(aes(x=x,y=y, group=group), size = 0.1)

enter image description here

while points are in pg[[1]][[2]]

ggplot(data= pg[[1]][[1]])+
  geom_line(aes(x=x,y=y, group=group), size = 0.1)+
  geom_point(data= pg[[1]][[2]], aes(x=x,y=y, group=group), color = "red")

enter image description here