Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot2 - plot alternating Y axes

Hello StackOverflow community, Is there a way in R ggplot2, using the facet_grid() function to get alternate Y axes like in this example :

(Example of multiple time series plot with alternating Y axes. Source : https://www.sciencedirect.com/science/article/pii/S0277379121004522)

Here are fake data from the economics dataset and ggplot code to reproduce :

library(ggplot2)
library(tidyverse)

data <- economics %>%
  select(date, unemploy, pop, psavert) %>%
  pivot_longer(cols = c(unemploy, pop, psavert), names_to = "variable", values_to = "value")

p <- ggplot(data, aes(x = date, y = value, color = variable)) +
  geom_line() +
  facet_grid(rows = vars(variable), scales = "free_y") +  # Create facets with free Y scales
  scale_y_continuous(
    sec.axis = sec_axis(~.) # Add a secondary axis
  )+
  theme(strip.text = element_blank(), 
        strip.background = element_blank(),
        axis.line = element_line(), 
        legend.position = "top")
 
print(p)
like image 368
Alex Avatar asked Oct 23 '25 12:10

Alex


1 Answers

  ... +
  ggh4x::facetted_pos_scales(y = list(
    scale_y_continuous(),
    scale_y_continuous(position = "right"),
    scale_y_continuous()
  )) + 
  theme(panel.spacing.y=unit(0, "lines")) + ...

enter image description here

like image 121
Jon Spring Avatar answered Oct 26 '25 11:10

Jon Spring



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!