2

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?

Chris
  • 1,197
  • 9
  • 28

2 Answers2

1

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)

agila
  • 3,289
  • 2
  • 9
  • 20
  • The key to the intervals is impossible to understand without additional information. The intervals shown are still overlapping. – Peter Pearman Mar 04 '20 at 09:36
  • @PeterPearman, I'm sorry but I don't understand your comment. Why do you say that the intervals are overlapping? For example the first interval represent those regions where HPI is greater or equal to 10 but less than 15, the second interval represent those region where HPI is greater than 15 but strictly less than 20 and so on. – agila Mar 04 '20 at 10:02
  • @PeterPearman Do you mean understanding what the difference between [ and ) mean in this context? https://stackoverflow.com/questions/4396290/what-does-this-square-bracket-and-parenthesis-bracket-notation-mean-first1-last – Chris Mar 04 '20 at 10:49
  • Yes, the [ and } are able to express the intervals, but it's not obvious and requires explanation. It is a work-around, a non-standard notation, and would never be acceptable for publication. Put it on your web page with your explanation. Fine. But one should be able to represent the intervals in an obvious way, using standard symbology, Expressing intervals in a way that requires explaining, when there are obvious ways to express the intervals correctly, simply isn't adequate. For count data, intervals of 10,14; 15,19; 20,24. For real numbers, using <, >, etc. Major tmap limitation. – Peter Pearman Mar 06 '20 at 08:43
1

I have managed to get it to work by using:

legend.format = list(format = "f", text.separator = "<"))
Bananafan
  • 31
  • 3
  • I would suggest legend.format = list(format = "f", text.separator = "to <")) might make it even clearer, but that is a useful answer. Thanks – Chris Apr 22 '21 at 17:01