Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

legend

tmap

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.

like image 776
Valentin Avatar asked Mar 08 '18 13:03

Valentin


2 Answers

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

like image 80
Jindra Lacko Avatar answered Sep 30 '22 13:09

Jindra Lacko


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

like image 28
francisco corvalan Avatar answered Sep 30 '22 12:09

francisco corvalan