rlabeltmapspatial-data

How to label only one point in tmap in r?


In the example below I would like to have only the label for Ghana in the tm_text("name") layer showing.

Any idea how to do this? Thank you for your help.

library(tmap)
data("World")
tmap_mode("view")

tm_shape(World) +
  tm_polygons("HPI", id="HPI")+tm_text("name")

Solution

  • This should give you what you require:
    The key line is: tm_shape(filter(World, name == "Ghana")) which uses dplyr::filter() to subset the name variable for the required name(s).
    With Ghana outlined in red to make it more obvious which country the label refers to.

    library(tmap)
    library(dplyr)
    
    data("World")
    
    
    tm_shape(World) +
      tm_polygons("HPI", id="HPI")+
      tm_shape(filter(World, name == "Ghana")) +
      tm_borders(col = "red")+
      tm_text("name", xmod = -1, ymod = -1)
    

    Created on 2021-04-12 by the reprex package (v2.0.0)