6

I try to draw a graph in map with R

code :

df<-data.frame("from" = c("Lyon", "Toulouse", "Paris", "Marseille"), 
               "to"= c("Paris", "Paris", "Marseille", "Toulouse"))
meta <- data.frame("name"=c("Lyon", "Toulouse", "Paris", "Marseille"), 
                   "lon"=c(-4.850000, 1.444209, 2.352222, 5.36978),  
                   "lat"=c(45.750000, 43.604652, 48.856614, 43.296482))

g <- graph.data.frame(df, directed=FALSE, vertices=meta)
lo <- layout.norm(as.matrix(meta[,2:3]))
plot.igraph(g, layout=lo,vertex.size = 60,
            vertex.color="red",
            vertex.frame.color= "white",
            vertex.label.color = "white",
            vertex.label.family = "sans",
            edge.width=2,  
            edge.color="black")

but I do not find a way that allows me to display it on the map using leaflet, someone has an idea please?

1 Answer 1

11

Here is one possible way, by first converting your graph to spatial object and using plotting these with with the leaflet package.

library(sp)
gg <- get.data.frame(g, "both")
vert <- gg$vertices
coordinates(vert) <- ~lon+lat

edges <- gg$edges

edges <- lapply(1:nrow(edges), function(i) {
  as(rbind(vert[vert$name == edges[i, "from"], ], 
           vert[vert$name == edges[i, "to"], ]), 
     "SpatialLines")
})


for (i in seq_along(edges)) {
  edges[[i]] <- spChFIDs(edges[[i]], as.character(i))
}

edges <- do.call(rbind, edges)


library(leaflet)
leaflet(vert) %>% addTiles() %>% addMarkers(data = vert) %>% addPolylines(data = edges)

enter image description here

You may want to improve the styling.

3
  • +1, thank you so much this is what I looking for , and if we want to draw the dotted line, how make it?
    – zina_GIS
    Dec 4, 2015 at 13:20
  • 2
    @zina_GIS: have a look at ?leaflet::addPolylines and in particular at the dashArray argument.
    – johannes
    Dec 4, 2015 at 13:23
  • exactly it's work with dashArray option thanks again
    – zina_GIS
    Dec 4, 2015 at 13:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.