[英]cannot remove grey background from PNG produced via ggsave()
I've been trying to save a flextable as a ggplot, then write it to a PNG for gridding.我一直在尝试将 flextable 保存为 ggplot,然后将其写入 PNG 进行网格化。 I've gotten what I need, except that the background of the resulting PNG is grey, like this:
我已经得到了我需要的东西,除了生成的 PNG 的背景是灰色的,就像这样:
Whereas the plot view of the ggplot looks like I want it to (but low res):而 ggplot 的 plot 视图看起来像我想要的(但分辨率低):
Here is the code I use to produce the images (flexRPOPS is a flextable object):这是我用来生成图像的代码(flexRPOPS 是一个 flextable 对象):
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')
The issue is that when you plot an empty plot, the default panel background is light gray.问题是当您 plot 为空 plot 时,默认面板背景为浅灰色。 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:这是一个来自
grid
的简单rectGrob
示例,可以为您提供这个想法:
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())
:使用
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)
.或者,您可以设置
theme.background = element_rect(fill=NA)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.