将 geom_raster 导出为具有特定像素尺寸/无 ggplot 边框的 tiff

Export geom_raster as tiff with specific pixel dimensions/ no ggplot borders

我正在 R 中处理光栅图像,目的是将处理后的图像导出为与输入数据具有相同尺寸的 tiff。我需要对 ggplot 中的数据应用一些审美过程(我不会在此 post 中讨论),这就是为什么我将其处理为 ggplot 而不是作为栅格。在 ggplot 中创建绘图后,我想以与输入栅格相同的分辨率导出为 tiff,没有线条或边距。

下面是一个示例数据集。您可以在下面的示例中看到输入栅格为 87 x 61 像素。我想导出尺寸完全相同的 tiff。以下是我的尝试。当我导出为 tiff 时,ggplot 包括我不想要的图周围的边距(我严格只想要与栅格中的输入单元格重合的输入单元格。

volcano_raster <- raster(volcano, xy = TRUE)

volcano_raster 
    # You can see below that the input raster is 87, 61 cells.
    class      : RasterLayer 
    dimensions : 87, 61, 5307  (nrow, ncol, ncell)
    resolution : 0.01639344, 0.01149425  (x, y)
    extent     : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
    crs        : NA 
    source     : memory
    names      : layer 
    values     : 94, 195  (min, max)
    volcano_raster_df <- volcano_raster %>% as.data.frame(., xy = TRUE) %>% rename(layer = 3)

volcano_gg <- ggplot() +
  geom_raster(data = volcano_raster_df,
              aes(x = x, y = y,
                  fill = layer)) +
  scale_fill_gradient(low = "black", high = 'red') +
  ggmap::theme_nothing()+
  theme(legend.position="none") +
  theme(plot.margin = grid::unit(c(0,0,0,0), "mm"),
        axis.ticks.length = unit(0, "pt"),
        axis.text=element_blank(),
        axis.title=element_blank()) +
  labs(x = NULL, y = NULL)

# Here I export the plot as a tiff using the same dimensions as those in the raster.
ggsave(plot=volcano_gg, "vol_gg_df.tiff", device = "tiff", units = 'px', width = 61, height = 86)

删除图例(在 scale... 级别),使用 theme_void() 并将 x- 和 y-axis 扩展设置为零对我有用。

## using "volcano_raster_df" from your example:
volcano_raster_df %>%
    ggplot() +
        geom_raster(aes(x, y, fill = layer)) +
        scale_fill_gradient(low = "black",
                            high = 'red',
                            guide = 'none' ## omit legend
                            ) +
        scale_x_continuous(expand = c(0, 0)) +
        scale_y_continuous(expand = c(0, 0)) +
        theme_void()

ggsave("vol_gg_df.tiff", device = "tiff",
        units = 'px', width = 61, height = 86)