Search code examples
rtmap

How to create a map with transparent background?


I'm trying to create and save a map with transparent background instead of a white (or any other color) one using the R package tmap.

Apart from what's in the example below, I tried using bg.color = "transparent", bg.color = NA, and bg.color = NULL in both tmap_options and tm_layout.

Version info:

  • tmap: 2.2
  • tmaptools: 2.0-1
library(tmap)
data("World")

tmap_options (bg.color = "#00000000", basemaps.alpha = 0)
map <- tm_shape(World) +
  tm_polygons("HPI") +
  tm_layout (frame = FALSE, bg.color = "#00000000")

tmap_save (map, filename = "~/test.png")

Am I doing something wrong or is this simply a limitation of the package? Thanks a lot!


Solution

  • I found a trick!

    I was looking for the same feature to draw a stack of maps in InDesign with outputs from R, tmap and I needed the background to be transparent.

    Here my solution, given your code:

    library(tmap)
    data("World")
    
    par(bg=NA)
    map <- tm_shape(World) +
      tm_polygons("HPI") +
      tm_layout (frame = FALSE, bg.color = "transparent")
    
    tmap_save (map, filename = "~/test.eps", bg="transparent") # Note the eps extension
    

    Caveat: testing this with different output formats, I realized that it doesn't work with png or jpg.