Search code examples
rggplot2raster

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


I am processing a raster image in R with the goal of exporting the processed image as a tiff with the same dimensions as the input data. There are aesthetic processes I need to apply to the data in ggplot (which I won't go into in this post) which is why I am processing it ggplot rather than as a raster. Once I have created the plot in ggplot I want to export as a tiff at the same resolution as the input raster, without the linework or margins.

Below is an example dataset. You can see in the example below that input raster is 87 x 61 pixels. I want to export a tiff with the exact same dimensions. Below is my attempt. When I export as a tiff ggplot includes margins around the plot which I do not want (I strictly want only the input cells which coincide with those from the raster.

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)

enter image description here


Solution

  • Removing legend (at the scale... level), using theme_void() and setting x- and y-axis expansion to zero did the trick for me.

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