How to overlay graphs with different Y Domains for Comparison

Hi! I'm new to R and am working through the R for Data Science online book. I wanted to try do some data frames of my own and decided to graph some weather data. I would like to show a line graph of the temperature and the barometric pressure to show the relationship between changes in the two. However, the Y domains for the two series are different enough that you can't really see the trend (temps in F are 60-90 range and pressure in millibars are 1000+). I'm only interested in the trend, not the specific Y values. I tried adding a second axis, but that didn't show what I wanted and I also thought maybe if there was a way to do 2 graphs with the X data points aligned vertically it would accomplish the same goal. Does any have any suggestions on the best way to tackle this (again, I'm very new to R so its possible there is an easy solution I haven't read about yet)?

Thanks in advance!

Reprex:

library(ggplot2)
library(tidyr)

df <- data.frame(
   ReadingDate = c("2019-08-19", "2019-08-20", "2019-08-21", "2019-08-22",
                   "2019-08-23"),
          LowP = c(1013.85, 1013.2, 1012.89, 1013.7, 1015.79),
         HighP = c(1016.53, 1016.73, 1015.86, 1015.45, 1019.11),
       LowTemp = c(68.3, 68.54, 68.66, 69.49, 62.7),
      HighTemp = c(86.89, 84.9, 81.43, 77.44, 70.27)
)

df %>%
  gather(key, value, LowP, HighP, LowTemp, HighTemp) %>%
  ggplot(aes(x=ReadingDate, y=value, color=key, group=key)) +
  geom_line()

Created on 2019-08-24 by the reprex package (v0.3.0)

Does this work for you?

library(tidyverse)
library(lubridate)

df <- data.frame(stringsAsFactors = FALSE,
    ReadingDate = c("2019-08-19", "2019-08-20", "2019-08-21", "2019-08-22",
                    "2019-08-23"),
    LowP = c(1013.85, 1013.2, 1012.89, 1013.7, 1015.79),
    HighP = c(1016.53, 1016.73, 1015.86, 1015.45, 1019.11),
    LowTemp = c(68.3, 68.54, 68.66, 69.49, 62.7),
    HighTemp = c(86.89, 84.9, 81.43, 77.44, 70.27)
)

df %>%
    gather(key, Value, -ReadingDate) %>%
    mutate(Variable = if_else(str_detect(key, "Temp"), "Temp", "Pressure"),
           ReadingDate = ymd(ReadingDate)) %>% 
    ggplot(aes(x=ReadingDate, y=Value, color=key)) +
    geom_line() +
    facet_wrap("Variable", nrow = 2, scales = "free_y")

Created on 2019-08-24 by the reprex package (v0.3.0.9000)

1 Like

Thanks andresrcs, this looks like it will work perfectly. I had found the facet_wrap but was ending up with 4 graphs. It didn't occur to me to introduce a grouping variable.

Thanks again for the help.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.