Search code examples
rggplot2ggmap

r ggmap - add annotation superimposed on map


Questions about map legend editing exist (e.g.), but not exactly what I need.

Using ggmap, how do I select points in a map and add annotations superimposed on the map? Take the following code:

Map <- get_map(location = 'Santiago, Chile', zoom = 6, maptype = "terrain")
Map <- ggmap(Map)
Points <- data.frame(lon=c(-71.82718,-71.31263),lat=c(-34.36935,-34.29322))
Map_Points <- Map + geom_point(data = Points,aes(x=lon,y=lat,size=6))

Chile + two points

So now I have a nice map with a few points. How do I write some annotation near one of the points?


Solution

  • Quite straightforward: 1

    Code

    library(ggrepel)                   # for the auto-repelling label
    Map + 
        geom_point(data = Points, 
                   aes(x = lon, y = lat),
                   size = 3) +
        geom_label_repel(data = Points, 
                         aes(x = lon, y = lat, label = name),
                         size = 3,
                         vjust = -2,
                         hjust = 1)
    

    Data

    library(tmaptools)                 # for the geocode lookup
    library(ggmap)
    santiago_coords <- rbind(as.numeric(paste(geocode_OSM("Santiago, Chile")$coords))) 
    Map <- get_map(location = santiago_coords, zoom = 6, maptype = "terrain")
    Map <- ggmap(Map)
    Points <- data.frame(lon=c(-71.82718,-71.31263),
                         lat=c(-34.36935,-34.29322),
                         name=c("Location One", "Location Two"))