Spatial Digger
Spatial Digger

Reputation: 1993

igraph add to geographic map

I'm using R for networks. I've used the 'network' package, but now using 'igraph'.

I can plot the igraph using geographic coords. I can plot a map using 'maptools'(readShapePoly).

How can I plot the igraph on top of the map?

I have tried new=FALSE and add=TRUE but it doesn't work, plotting the igraph object always overwrites.

greece <- readShapePoly.("Z:/GeoData/World_data/Basemaps/Greece/GRC_adm1.shp")

df<-data.frame("from" = c.("Athens", "Iraklio", "Thessaloniki", "Patra"), "to"= c("Thessaloniki", "Thessaloniki", "Athens", "Iraklio"))
meta <- data.frame("name"=c("Athens", "Iraklio", "Thessaloniki", "Patra"), 
               "lon"=c(23.72800,25.13356,22.94090,21.73507),  
               "lat"=c(37.98415,35.33349,40.63229,38.24628))


#plot it
g <- graph.data.frame(df, directed=T, vertices=meta)
lo <- layout.norm(as.matrix(meta[,2:3]))
plot(greece)
plot.igraph(g, layout=lo, add = T)

I've seen this solution, but I don't want to use the cario library as I'm using geographic data, not an image as base plot. Using geo-coordinates as vertex coordinates in the igraph r-package

Upvotes: 4

Views: 5505

Answers (1)

lukeA
lukeA

Reputation: 54237

You can do it like this:

library(raster)
library(igraph)
greece <- getData('GADM', country='GRC', level=1)
df<-data.frame("from" = c("Athens", "Iraklio", "Thessaloniki", "Patra"), "to"= c("Thessaloniki", "Thessaloniki", "Athens", "Iraklio"))
meta <- data.frame("name"=c("Athens", "Iraklio", "Thessaloniki", "Patra"), 
               "lon"=c(23.72800,25.13356,22.94090,21.73507),  
               "lat"=c(37.98415,35.33349,40.63229,38.24628))
g <- graph.data.frame(df, directed=T, vertices=meta)
lo <- as.matrix(meta[,2:3])
plot(greece)
plot(g, layout=lo, add = TRUE, rescale = FALSE)

Obviously you don't want to normalize your layout coordinates to a scale from -1 to 1, because your geo plot does not use that scale. So no layout.norm(). However, it seems that the latest igraph automatically normalizes the coordinates by default under the hood. At first, I didn't find the responsible rescale parameter in the documentation and had to use debug(plot.igraph) to trace and see it. (Although it's documented in ?igraph.plotting.) If you set rescale=FALSE and add=TRUE, then it should work as expected.

enter image description here

Upvotes: 6

Related Questions