Suppose that I have two variables with different scales for example;
df = data.table::data.table(
date = seq(from = lubridate::ymd("2010-01-01"),
to = lubridate::ymd("2020-01-01"), length = 100),
var1 = rpois(n = 100, lambda = 84),
var2 = rpois(n = 100, lambda = 300)
)
If I decide to use a double y-axis plot, using the code;
library(ggplot)
df |>
ggplot(aes(x = date)) +
geom_line(aes(y = var1), col = "royalblue") +
geom_line(aes(y = var2), col = "red") +
scale_y_continuous(
name = "var1",
sec.axis = sec_axis(~., name = "var2")
) +
theme_light()
The results are as follows;
How can I adjust the limits of the second y-axis to, for instance, start at 250 and end at 400? This would bring the lines closer together, allowing for a clearer view of the trend.
>Solution :
You can transform the data when you plot and then undo the transformation in the call to sec_axis(). Here, I just subtracted 200 from the data values and then add 200 to the labels to reflect the change:
library(ggplot2)
library(data.table)
library(lubridate)
df = data.table(
date = seq(from = ymd("2010-01-01"), to = ymd("2020-01-01"), length = 100),
var1 = rpois(n = 100, lambda = 84),
var2 = rpois(n = 100, lambda = 300)
)
df |>
ggplot(aes(x = date)) +
geom_line(aes(y = var1), col = "royalblue") +
geom_line(aes(y = var2-200), col = "red") +
scale_y_continuous(
name = "var1",
sec.axis = sec_axis(~.+200, name = "var2")
) +
theme_light()

Created on 2024-01-25 with reprex v2.0.2
