Search code examples
rggplot2scaleaxis-labelspatchwork

Change axes label and scale using ggplot and patchwork in R


(I am trying to make this question as short and concise as possible, as other related answers may be tough for the non-savvy like myself.)

With the following code in mind, is it possible to have both y-axes on the same scale (that of the graph with the highest y-limit), and to have independent labels for each of the axes (namely the y-axes)? I tried to use facet_wrap but haven't so far been able to succeed as Layer 1 is missing)

library(ggplot2)
library(patchwork)
d <- cars
d$Obs <- c(1:50)
f1 <- function(a) {
  ggplot(data=d, aes_string(x="Obs", y=a)) +
    geom_line() +
    labs(x="Observation",y="Speed/Distance")
}
f1("speed") + f1("dist") 

Speed and distance graphs using cars


Solution

  • You could add two additional arguments to your function, one for the axis label and one for your desired limits.

    library(ggplot2)
    library(patchwork)
    d <- cars
    d$Obs <- c(1:50)
    
    f1 <- function(a, y_lab) {
      ggplot(data = d, aes_string(x = "Obs", y = a)) +
        geom_line() +
        scale_y_continuous(limits = range(c(d$speed, d$dist))) +
        labs(x = "Observation", y = y_lab)
    }
    
    f1("speed", "Speed") + f1("dist", "Distance")