0

I am trying to export rasters from the rasterViz package as jpg or png. I am struggling to:

  • completely trim white border
  • keep transparency for NAs

So far:

library(raster)
library(rasterVis)

# Toy Data
m <-  matrix(seq(0,100,length.out=15000),150,100)
r <- raster(m, xmn=0,ymn=0,xmx=nrow(m),ymx=ncol(m))

jpeg(file = "test.jpg", bg = "transparent", height=nrow(r), width=ncol(r))

levelplot(t(r), contour=T, margin=F, scales = list(draw=FALSE), colorkey=NULL,
 par.settings = list(axis.line = list(line=0), mar=c(0,0,0,0), omi=c(0,0,0,0), 
                          xaxt='n', yaxt='n', bg='transparent'))
dev.off()

...still has a white border and transparency isn't working (for the border at least). I'm also a little confused about needing to transpose the raster to plot.

For context; I need to preserve the aspect ratio and exactly trim to the extends so that I can use the images as map tiles elsewhere. It isn't feasible to do manual post processing.

freds
  • 1
  • 3

1 Answers1

1

Only png() supports transparent backgrounds.

png(file = "test.png", bg = "transparent", height=nrow(r), width=ncol(r))

png supports transparent backgrounds: use bg = "transparent". (Not all PNG viewers render files with transparency correctly.) When transparency is in use in the type = "Xlib" variant a very light grey is used as the background and so appears as transparent if used in the plot. This allows opaque white to be used, as in the example. The type = "cairo", type = "cairo-png" and type = "quartz" variants allow semi-transparent colours, including on a transparent or semi-transparent background.

Christopher Stephan
  • 1,081
  • 16
  • 33