【问题标题】:cannot remove grey background from PNG produced via ggsave()无法从通过 ggsave() 生成的 PNG 中删除灰色背景
【发布时间】:2021-12-29 15:55:05
【问题描述】:

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

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

这是我用来生成图像的代码(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')

【问题讨论】:

    标签: r ggplot2 png flextable


    【解决方案1】:

    问题在于,当您绘制空图时,默认面板背景为浅灰色。这就是您所看到的,因此您需要将面板背景设置为空白(或透明),然后它应该可以工作。这是一个来自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')
    

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-24
      • 2014-12-31
      • 1970-01-01
      • 2012-08-19
      • 1970-01-01
      • 2012-03-20
      • 1970-01-01
      • 2021-10-28
      相关资源
      最近更新 更多