(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")
CodePudding user response:
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, ylim = NULL) {
ggplot(data = d, aes_string(x = "Obs", y = a))
geom_line()
scale_y_continuous(limits = ylim)
labs(x = "Observation", y = y_lab)
}
ylim <- range(c(d$speed, d$dist))
f1("speed", "Speed", ylim = ylim) f1("dist", "Distance", ylim = ylim)
CodePudding user response:
Reshape wide-to-long, then use facet. Instead of having different y-axis labels we will have facet labels:
library(ggplot2)
library(tidyr)
pivot_longer(d, 1:2, names_to = "grp") %>%
ggplot(aes(x = Obs, y = value))
geom_line()
facet_wrap(vars(grp))