Honouring transparency when saving lattice graphics as png images on Windows


Coming against my ignorance of lattice graphics as someone who learned R after ggplot2 came on the scene. I maintain a package that relies on an older package written using lattice graphics.

I would like the outputs to be transparent, but it appears that the transparency only applies to the white plot area, not the actual rasters.

The code looks like this:

plt <- openair::polarPlot(openair::mydata, alpha = .5)

png(filename = "testplot.png", bg = "transparent")

And putting the output, "testplot.png", over a blue square looks like this. Note that the actual surface isn't transparent, it is just washed out.


The code for openair::polarPlot() can be found here, but I'm not expecting anyone to go through it unless you are particularly keen! The relevant part is reproduced below, where transparency is controlled using alpha.regions.

          x, y, z,
          at = col.scale,
          pretty = TRUE,
          col.regions = col,
          labels = FALSE, alpha.regions = alpha

Interestingly, this appears to "just work" on Mac computers, but it doesn't play ball on Windows machines and you get this "washed out" appearance.

I appreciate one answer is "use ggplot2" which we are working on, but at this stage I'd prefer a fix within lattice to avoid all of the various knock-on effects of refactoring openair just for the sake of fixing transparency.

Note that I am in the position to make changes to openair if needed.


As always, just after I post I find the solution!

Specify type in png(), e.g.,

    grDevices::png(type = "cairo-png",
      filename = paste0(dir, "/", id, "_", split, ".png"),
      width = fig.width * 300,
      height = fig.height * 300,
      res = 300,
      bg = "transparent"
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.