Search code examples
rggplot2ggmap

Connecting 2 points in a map using ggplot


I have the following code to plot 2 points in ggmap

library(ggmap)
library(ggplot2)

d <- data.frame(lat=c(12.97131,12.98692),
        lon=c(77.5121,77.68627))

Bangalore <- get_map("Bangalore,India", zoom=12)

p <- ggmap(Bangalore)
p + geom_point(data=d, aes(x=lon, y=lat),color="red",size=3)

ggplot(p)

These points are showing as red dots in the map. How can I connect these points?


Solution

  • No need for the final ggplot(p) (that's probably throwing an error on your end) and I'd use geom_path:

    p <- ggmap(Bangalore)
    p <- p + geom_point(data=d, aes(x=lon, y=lat),color="red",size=3)
    p + geom_path(data=d, aes(x=lon, y=lat), color="black", size=1)
    ## or....
    p + geom_line(data=d, aes(x=lon, y=lat), color="black", size=1)
    

    enter image description here