R tmap, legend formatting - display single value in the first legend key
Asked Answered
F

2

8

I'm not sure how or if is possible to adjust the key legends in the fallowing way. Consider the example:

library(tmap)
data(Europe)

my_map <- 
  tm_shape(Europe) +
  tm_polygons("well_being", textNA="Non-European countries", title="Well-Being Index") +
  tm_text("iso_a3", size="AREA", root=5) +
  tm_layout(legend.position = c("RIGHT","TOP"),
            legend.frame = TRUE)

enter image description here

I tried legend.format = list(scientific = TRUE) in something like:

my_map2 <- my_map +
  tm_layout(legend.format = list(scientific = TRUE))

which gives this for a legend:

enter image description here

However, what I wish is something like:

enter image description here

In my data, the 4 is a zero, and I was asked to make it stand out as zero alone.

Ferrous answered 8/3, 2018 at 13:33 Comment(0)
O
5

As far as I know this is impossible by using tmap legend formatting alone - there will always be the little separator. Either "to" or whatever you overwrite it with text.separator from legend.format call.

What you need is one extra step in your data processing - you must create a special variable with your labels, and plot according to this. You have full control over the levels, so you can have the first one as standalone zero.

For simplicity sake I am using ifelse to split into two levels (plus the NAs for Non-European countries), but you can get more fancy than that...

Europe <- Europe %>%
  st_as_sf() %>%  # from sf package - makes Europe behave as a data.frame
  mutate(well_being_adj = ifelse(well_being < 5, "0", "more than five"))

my_map <- 
  tm_shape(Europe) +
  tm_polygons("well_being_adj", textNA="Non-European countries", title="Well-Being Index") +
  tm_text("iso_a3", size="AREA", root=5) +
  tm_layout(legend.position = c("RIGHT","TOP"),
            legend.frame = TRUE)
print(my_map)

enter image description here

Onym answered 9/3, 2018 at 9:1 Comment(2)
This is an elegant solution! Instead of ifelse I used cut function as it allows to define labels and breaks.Medusa
Glad to be of service! The ifelse was just a hack, the key part is creating the buckets / labels yourself, with full control over labeling :)Onym
C
5

Despite being solved, another more practical alternative is to modify the levels in tm_polygons labels

tm_polygons(labels = c ("0", "more than five")

This way also serves for rasters files

Capitate answered 15/4, 2019 at 21:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.