Search code examples
rggplot2patchwork

side-by-side ggplot2 with patchwork


I would like to plot the following to images side by side please?

library(ggplot2)
library(patchwork)

# Plot the DEMs
p1 <- ggplot(dem %>% as.data.frame(xy = TRUE)) +
  geom_raster(aes(x = x, y = y, fill = `10m_BA`)) +
  scale_fill_gradientn(colors = terrain.colors(100))
p2 <- ggplot(dem30 %>% as.data.frame(xy = TRUE)) +
  geom_raster(aes(x = x, y = y, fill = `10m_BA`)) +
  scale_fill_gradientn(colors = terrain.colors(100))

# Combine the plots side by side
combined_plot <- p1 + p2 + plot_layout(ncol = 2, guides = "collect")

# Display the combined plot
combined_plot

enter image description here

How can I share the y-axis and the legend please?


Solution

  • You can use facet_wrap with pivot_longer like the following

    library(tidyverse)
    library(raster)
    
    f <- system.file("ex/elev.tif", package="terra")
    r1 <- stack(f)
    r2 <- stack(f)
    
    r <- stack(r1, r2)
    
    ggplot(r %>% as.data.frame(xy = TRUE) %>% 
             pivot_longer(-c(x, y))) +
      geom_raster(aes(x = x, y = y, fill = value)) +
      facet_wrap(name~.) +
      scale_fill_gradientn(colors = terrain.colors(100))
    

    enter image description here