简体   繁体   中英

Tmap: customize continuous legend values without changing scale

I would like to change the numbers of a legend without changing the scale in tmap.

As an example:

r <- raster::raster(matrix(runif(100), 10, 10))
tm_shape(r) +
    tm_raster(legend.is.portrait = FALSE, style = 'cont', title = '', palette = "-RdBu") +
    tm_layout(frame = FALSE, legend.outside = TRUE, legend.outside.position = "bottom")

Gives us a legend that looks like this:

在此处输入图片说明

We can alter the breaks in the tm_raster call like this:

tm_shape(r) +
    tm_raster(legend.is.portrait = FALSE, style = 'cont', title = '', palette = "-RdBu",
    breaks = pretty(cellStats(r, range), 3),) +
    tm_layout(frame = FALSE, legend.outside = TRUE, legend.outside.position = "bottom")

This gives us a legend that looks different from the first:

在此处输入图片说明

What I want to do is draw the legend in the first example, but only have labels at 0.2, 0.5, and 0.8.

You can pass a labelling function to the legend.format parameter of tm_layout . For example, if you want a wide legend bar with labels at 0.2, 0.5 and 0.8, you create more breaks but only label those that you want:

tm_shape(r) +
    tm_raster(legend.is.portrait = FALSE, style = 'cont',
              title = '', palette = "-RdBu", 
              breaks = c(0, 0.2, 0.4, 0.5, 0.6, 0.8, 1)) +
    tm_layout(frame = FALSE, legend.outside = TRUE, 
              legend.outside.position = "bottom",
              legend.format = list(fun = function(x) {
                ifelse(x %in% c(0.2, 0.5, 0.8), x, "")
                }))

在此处输入图片说明

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