R tmap modify legends dynamically to prevent overlapping legend values

Viewed 737

Is there a way to prevent overlapping values in legends in tmap dynamically?

Take this example:

library(tmap)
data("World")
tm_shape(World) +
tm_polygons("HPI", n=7)

The legend does not make it clear what category values of 15, 20, 25, 30, 35 or 40 belong to.

One solution would be this:

 tm_shape(World) +
 tm_polygons("HPI", n=7,
   labels = c("0 to 15", ">15 to 20", ">20 to 25", ">25 to 30", ">30 to 35", ">35 to 40", ">40 to 45"))

However, you will obviously have to change this manually every time you have different n values for the number of categories.

Can a similar output be generated automatically no matter how categories are used in a map?

2 Answers

The following code creates a square bracket from a closed interval (i.e. >=) and a "simple" bracket for an open interval (i.e <). Is this a reasonable solution? You can also read more details at the legend.format argument.

library(tmap)
#> Warning: replacing previous import 'sf::st_make_valid' by
#> 'lwgeom::st_make_valid' when loading 'tmap'
data("World")
tm_shape(World) +
  tm_polygons("HPI", n = 7, legend.format = list(scientific = TRUE, format = "f"))

Created on 2020-03-03 by the reprex package (v0.3.0)

I have managed to get it to work by using:

legend.format = list(format = "f", text.separator = "<"))
Related