Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to change the scale limits of the second y-axis in ggplot2?

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading