tmap icon indicating copy to clipboard operation
tmap copied to clipboard

Can one add custom text in legend text?

Open MatthieuStigler opened this issue 5 years ago • 3 comments

Hi

I am using a quantile scale and hence would like to add in front of each of the legend group, their relative quantile, i.e. 0.2 to 0.4 would become Q1: 0.2 to 0.4. Is there an easy way to do this with the current code? or should I use tm_add_legend instead?

I tried playing with the tm_layout(legend.format = list(fun=... argument, but not very successful so far .

Thanks!

library(tmap)
#> Warning: replacing previous import 'sf::st_make_valid' by
#> 'lwgeom::st_make_valid' when loading 'tmap'
data(World)
tm_shape(World) + 
  tm_fill("inequality", style = "quantile") +
  tm_layout(legend.format = list(fun=function(x) paste0("Q", 1:5, ": ", as.character(round(x, 2)))))

Created on 2020-04-21 by the reprex package (v0.3.0)

MatthieuStigler avatar Apr 21 '20 19:04 MatthieuStigler

I thought maybe a more sophisticated list would fix it, but it, er, doesn't 😩 If I have any better ideas I'll let you know!

library(tmap)

q_list <- c(rbind(paste0("Q", 1:5, ": "), ""))

data(World)
tm_shape(World) + 
  tm_fill("inequality", style = "quantile") +
  tm_layout(legend.format = list(fun=function(x) paste0(q_list, as.character(round(x, 2)))))

Created on 2020-04-22 by the reprex package (v0.3.0)

francisbarton avatar Apr 22 '20 10:04 francisbarton

This cannot be done at the moment. It's probably too complex, but if someone has an idea how this can be done in a user-friendly way, let me know.

mtennekes avatar Apr 26 '20 21:04 mtennekes

library(tmap)
#> Warning: replacing previous import 'sf::st_make_valid' by
#> 'lwgeom::st_make_valid' when loading 'tmap'
data(World)
tm_shape(World) + 
  tm_fill("inequality", style='fixed', 
          breaks = c(0.04, 0.12, 0.19, 0.24, 0.37, 0.51),
          labels = c('Q1: 0.04-0.12', 'Q2: 0.12-0.19', 'Q3:0.19-0.24',
                     'Q4: 0.24-0.37', 'Q5: 0.37-0.51'))
Screen Shot 2020-05-06 at 10 26 28 AM

You can manually define it if you already know what the quantile breaks are. It is probably hard to reproduce for a large number of maps, but if you only need to make one, the codes above work well.

xiaofanliang avatar May 06 '20 14:05 xiaofanliang