2

I have a graph created with igraph where each node has a spatial location with lat and long. I would like to use ggraph to plot this network using these spatial coordinates to define the position/layout of nodes. Any ideas on how to do this?

I know it is possible to do this in igraph (see reproducible example below) but I'd prefer doing this with ggraph, particularly because I would like to add a ggmap layer to the plot.

reproducible example

library(igraph)
library(ggraph)

# create network
  # nodes
  actors <- data.frame(name=c("Alice", "Bob", "Cecil", "David","Esmeralda"),
                       age=c(48,33,45,34,21),
                       gender=c("F","M","F","M","F"),
                        long=c(-43.17536, -43.17411, -43.36605, -43.19155, -43.33636),
                        lat=c(-22.95414, -22.9302, -23.00133, -22.90353, -22.87253))

  # edges  
  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))

# Graph
  g <- graph_from_data_frame(relations, directed=TRUE, vertices=actors)

Plot network with spatial coordinates using igraph

# get lat long coordinates for the layout
  lo <- layout.norm(as.matrix(actors[, c("long","lat")]))

#plot
  plot.igraph(g, layout=lo, rescale=T, vertex.label= NA)

enter image description here

rafa.pereira
  • 13,251
  • 6
  • 71
  • 109

1 Answers1

3

You can add the coordinates directly to the graph object in igraph by setting the an X and Y attributes to the vertices. ggraph will recognise the attributes and plot the vertices accordingly.

V(g)$x<-lo[,1]
V(g)$y<-lo[,2]

#plot
ggraph(g)+
  geom_edge_link()+
  geom_node_point()
  • 1
    Thanks @Mateo! That's more simple than I thought. Any idea on how to combine a `ggpraph` plot with a `ggmap` ? – rafa.pereira May 08 '17 at 20:38
  • 1
    Haven't tried it. My approach is to turn the graph along with the calculated measures of interest to a `data.frame` and use `ggplot2` and `autoplot` from the `OpenStreetMap` library. Here is an example: [graph plot](https://github.com/mateoneira/UrbanSim_networks/blob/master/plotting_graph.R). Hope it helps – Mateo Neira May 09 '17 at 23:52
  • Hey, this is super useful, but do you know how to put the real coordinates on x and y axes ? Because I am just getting a network range. – DSA Dec 17 '18 at 17:14