I've been trying to save a flextable as a ggplot, then write it to a PNG for gridding. I've gotten what I need, except that the background of the resulting PNG is grey, like this:
Whereas the plot view of the ggplot looks like I want it to (but low res):
Here is the code I use to produce the images (flexRPOPS is a flextable object):
library(flextable); library(ggplot2); library(png); library(magick);library(webshot)
flexRPOPS_raster <- as_raster(flexRPOPS, zoom = 20, webshot="webshot")
flexRPOPS_raster <- image_trim(flexRPOPS_raster, fuzz = 10)
flexRPOPS_ggplotex <- ggplot() annotation_custom(rasterGrob(flexRPOPS_raster), xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf)
flexRPOPS_compare_ex1 <- ggsave(filename = "deptovr_ex1.png", flexRPOPS_ggplotex, width = flexRPOPS_dims$widths, height = flexRPOPS_dims$heights, dpi = 600, units = "in", bg="#ffffff", device='png')
CodePudding user response:
The issue is that when you plot an empty plot, the default panel background is light gray. That's what you're seeing, so you need to set the panel background to blank (or transparent), then it should work. Here's an example with a simple rectGrob
from grid
to give you the idea:
library(ggplot2)
library(grid)
p <- ggplot() annotation_custom(grob=rectGrob(width=0.5, height=0.5))
p
ggsave('a_gray.png', bg='#ffffff')
Set the panel background to be blank using theme(panel.background=element_blank())
:
p theme(panel.background = element_blank())
ggsave('a_white.png', bg='#ffffff')
Alternatively, you can set theme.background = element_rect(fill=NA)
.