1

I'm trying to change the alpha value of my legend to match that of the polygon fill, however nothing seems to happen when I specify the alpha argument in tm_add_legend. Is there something blindingly obvious that i'm missing here?

library(tmap)
library(sf)

nc <- st_read(system.file("shape/nc.shp", package="sf"))

tm_shape(nc) + 
tm_polygons(col = "#326abf", border.col = "white", lwd = 2, alpha = 0.5) +
tm_add_legend(type = "fill", 
              alpha = 0.5,
              labels = "NC",
              col = "#326abf")

enter image description here

jazzurro
  • 23,179
  • 35
  • 66
  • 76
geo_rkal
  • 43
  • 4

1 Answers1

3

I am not sure how tmap exactly works in this case. But I found a workaround. I created a dummy variable called mycat. Then, I used this variable for col in tm_polygons() and specify the color you are using in palette. In this way, you do not have to use tm_add_legend().

library(dplyr)
library(sf)
library(tmap)

mutate(nc, mycat = "one") -> nc

tm_shape(nc) +
tm_polygons(col = "mycat", 
            palette = "#326abf",
            border.col = "white", lwd = 2, alpha = 0.5,
            title = "",
            labels = "NC") 

enter image description here

jazzurro
  • 23,179
  • 35
  • 66
  • 76
  • That's a neat workaround, thanks! I'm still curious as to why alpha is not doing what I think it should be doing. – geo_rkal Jan 22 '20 at 08:57
  • @geo_rkal I am not familiar with tmap. But it seems that `tm_add_legend()` is not linked to `tm_polygons()`. I have the impression that it is creating a custom/manual legend. If you check some examples of tmap, you do not see they use `tm_add_legend()`. In these examples, I saw that they actually assigned a variable to `col` as I did. In the way you wrote your code, you manually assigned one color to `col`. This is like the difference of whether you have `fill` in `aes()` or not in ggplot. Somehow tmap does not like your way. – jazzurro Jan 22 '20 at 09:23
  • @geo_rkal So my conclusion was to use `col` as if it were in `aes()` in ggplot. In this way, we can create the graphic above. I hope this explanation helps you to some extent. – jazzurro Jan 22 '20 at 09:30
  • Yes that makes sense. And you're right, `tm_add_legend` makes a manual legend but it doesn't seem to accept all the arguments in the way i thought it did. I'll stick to your method, – geo_rkal Jan 22 '20 at 09:30