Search code examples
rgeotmap

How to highlight locations on a tmap in R?


I am trying to use tm_text to add text to define locations on a map using the tmap package in R.

This is the code i have used to produce my map:

library(tmap)
library(spData)

     tm_shape(nz) +
          tm_fill("Population") +
          tm_borders() +
          tm_layout(basemaps = leaflet::providers$Esri.WorldTopoMap)

I can not find another base map which would highlight the locations on the map that I am interested in so I was wondering whether there is a way I can over lay text into certain areas?

For example in the image below I would like to add text to highlight central hawks bay district and palmerton North.

Image


Solution

  • To add text to a tmap map via the tm_text() call you need two things - a label, and a location.

    With a little help of google maps I have found coordinates for Palmerston North and Central Hawke's Bay (never heard of either before :) and I propose the following solution:

    library(tmap)
    library(spData)
    library(sf)
    
    points <- data.frame(name = c("Central Hawke's Bay", "Palmerston North"),
                         x = c(176.474193, 175.611667),
                         y = c(-39.922303, -40.355),
                         stringsAsFactors = F)
    
    points <- st_as_sf(points, coords = c("x", "y"), crs = 4326)
    
    tmap_mode("view")
    
    tm_shape(nz) +
      tm_fill("Population") +
      tm_borders() +
      tm_shape(points) + tm_text("name") +
      tm_basemap(leaflet::providers$Esri.WorldTopoMap)
    

    I have included a library call to {sf} to facilitate conversion of coordinates as number to spatial data frame. I have also slightly amended your {tmap} call to suit current tmap best practices.

    enter image description here