无法从通过 ggsave() 生成的 PNG 中删除灰色背景

cannot remove grey background from PNG produced via ggsave()

我一直在尝试将 flextable 保存为 ggplot,然后将其写入 PNG 以进行网格化。我已经得到了我需要的东西,除了生成的 PNG 的背景是灰色的,像这样:

而 ggplot 的绘图视图看起来像我想要的(但分辨率低):

这是我用来生成图像的代码(flexRPOPS 是一个灵活的对象):

 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')

问题是当您绘制空图时,默认面板背景为浅灰色。这就是您所看到的,因此您需要将面板背景设置为空白(或透明),然后它应该可以工作。这是一个简单的 rectGrob 来自 grid 的例子来给你这个想法:

library(ggplot2)
library(grid)

p <- ggplot() + annotation_custom(grob=rectGrob(width=0.5, height=0.5))
p
ggsave('a_gray.png', bg='#ffffff')

使用theme(panel.background=element_blank())设置面板背景为空白:

p + theme(panel.background = element_blank())
ggsave('a_white.png', bg='#ffffff')

或者,您可以设置 theme.background = element_rect(fill=NA)