Search code examples
ggplot2patchwork

ggplot2 + patchwork: alignment of y-axis


i made 3 plots with ggplot2 and arranged it with patchwork. Since one of the plots only has positive values, one only negative and the third both positive and negative values, i have trouble to align the y-axis (y=0) for all three plots at the same height. Is there a way to do this via patchwork, or do i have to change the whole data preparation?

Thanks a lot for any help!

This is my code:

plot_1 <- ggplot() +
  geom_bar(
    data = data_p1, 
    aes(fill = SF, y = Anzahl, x = year), 
    position = 'stack', stat = 'identity') +
  labs(
    title = "title 1",
    x = "",
    y = "",
    fill = ""  
  ) +
  scale_y_continuous(labels = function(x) format(x, big.mark = ".")) + 
  scale_fill_manual(values = farben) +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 11, face = "bold"),
    axis.text.y = element_text(size = 8),
  ) 

plot_2 <- ggplot() +
  geom_bar(
    data = data_p2_1, 
    aes(fill = SF, y = Anzahl, x = year), 
    position = 'stack', stat = 'identity') +
  labs(
    title = "",
    x = "",
    y = "",
    fill = ""  
  ) +
  scale_y_continuous(labels = function(x) format(x, big.mark = ".")) + 
  scale_fill_manual(values = farben) +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 11, face = "bold"),
    axis.text.y = element_text(size = 8)
  ) +
  geom_bar(
    data = data_p2_2, 
    aes(fill = SF, y = Anzahl*-1, x = year), 
    position = 'stack', stat = 'identity') +
  labs(
    title = "title 2",
    x = "",
    y = "",
    fill = ""  
  ) +
  scale_y_continuous(labels = function(x) format(x, big.mark = ".")) + 
  # scale_fill_manual(values = farben) +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 11, face = "bold"),
    axis.text.y = element_text(size = 8)
  ) 

plot_3 <- ggplot() +
geom_bar(
  data = data_p3, 
  aes(fill = SF, y = Anzahl*-1, x = year), 
  position = 'stack', stat = 'identity') +
  labs(
    title = "title 3",
    x = "",
    y = "",
    fill = ""  
  ) +
  scale_y_continuous(labels = function(x) format(x, big.mark = ".")) + 
  scale_fill_manual(values = farben) +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 11, face = "bold"),
    axis.text.y = element_text(size = 8)
  )

patchwork <- plot_1 + plot_2 + plot_3 

result


Solution

  • Looking at the code here, using & ylim() should give multiple aligned plots:

    library(tidyverse)
    library(patchwork)
    
    data_a <- tibble(a = letters[1:5],
                     b = sample(20:100, 5))
    
    
    p1 <- data_a |> 
      ggplot(aes(a, b)) + 
      geom_col()
    
    p2 <- data_a |> 
      ggplot(aes(a, b * -1)) +
      geom_col()
    
    
    p1 + p2 & ylim(-100, 100)