简体   繁体   中英

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

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)

在此输入图像描述

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:

在此输入图像描述

However, what I wish is something like:

在此输入图像描述

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

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)

在此输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM