rggplot2yaxis

How to Create a Plot with Multiple Independent Y-Axes for Different Measurements in ggplot2?


I would like to plot multiple measurements recorded simultaneously over time. The value ranges of these parameters are independent of each other. I would like to have a separate y-axis with independent scaling for each measurement. In the example, the left y-axis should be shared between VO2 and VCO2, but each parameter should have its own y-axis (side by side) with its own scaling. The right y-axis for power should also be independent of the scaling of the left axes. Is this possible with ggplot2? I would appreciate any tips and help!

library(ggplot2)

d <- data.frame(
  time = seq(1, 600, by = 1),
  VO2 = c(rnorm(120, 250, 10), rnorm(120, 300, 15), seq(300, 2000, length.out = 240), rnorm(120, 300, 15)),
  VCO2 = c(rnorm(120, 200, 10), rnorm(120, 250, 15), seq(250, 1800, length.out = 240), rnorm(120, 250, 15)),
  power = c(rep(0, 120), rep(0, 120), seq(0, 160, length.out = 240), rep(0, 120))
)

ggplot(d, aes(x = time)) +
  geom_line(aes(y = VO2, color = "VO2"), linewidth = 1) +
  geom_line(aes(y = VCO2, color = "VCO2"), linewidth = 1) +
  geom_line(aes(y = power, color = "Power"), linewidth = 1) +
  scale_y_continuous(
    name = "VO2 and VCO2",
    sec.axis = sec_axis(~ . * (250 / max(d$power)), name = "Power (Watt)", breaks = seq(0, 250, by = 50))
  ) +
  scale_color_manual(values = c("VO2" = "blue", "VCO2" = "red", "Power" = "green")) +
  theme_minimal() +
  theme(
    axis.title = element_text(color = "black"),
    axis.text = element_text(color = "black"),
    axis.ticks = element_line(color = "black", linewidth = 1),
    axis.line = element_line(color = "black", linewidth = 1),
    axis.title.y.right = element_text(color = "black")
  )

Solution

  • An y-axis with scaling separate from another y axis is not possible in ggplot2, because the main author of the package believes separate y axes are flawed.

    I also don't think a third y axis is therefore possible.

    A related question (regarding independent secondary y axis) is asked here and possible solutions are provided there too: https://stackoverflow.com/a/3101876/26134966