ggplot2 为 value 和 date/datetime 指定辅助轴

ggplot2 specify a secondary axis for both value and date/datetime

我正在尝试生成 graph where I can compare two time periods without indexing the data. So, that I get one time-window running along the x-axis at the bottom and one along the x-axis at the top, kinda like the the example from the manual page(请参阅链接页面底部的图表)。

但是我也想在 y 轴上有双轴,像这样(使用下面的代码通过复制粘贴实现),

economics_long %>% filter(variable== "pce" & date  > "2008-01-01" & date < "2010-01-01") %>% 
  ggplot(aes(date, value01, colour = variable)) + geom_line()

economics_long %>% filter(variable== "pce" & date  > "1990-01-01" & date < "1992-01-01") %>% 
  ggplot(aes(date, value01, colour = variable)) + geom_line()

我想我需要使用 bind_rows() 将两个时间段剪掉并将它们放在最上面,并且可能会创建一个新变量,例如 variable 和两个选项,例如 time-window 1time-window 2,但是我想在开始手动构建一些疯狂的东西之前先在这里问一下。也许其他人也做过类似的事情?

我已经迈出了第一步,比如,

tw01 <- economics_long %>% 
filter(variable== "pce" & date  > "2008-01-01" & date < "2010-01-01")
tw02 <- economics_long %>% 
filter(variable== "pce" & date  > "1990-01-01" & date < "1992-01-01")

tw02$date <- tw01$date
tw <- bind_rows(tw01, tw02, .id = "time_window")
tw %>% ggplot(aes(date, value01, colour = time_window)) + geom_line()

也许这就是您要找的:

  1. 对于日期转换,我使用 lubridate::years。另外,为了在 sec_axis 内进行转换,我将包装到 hms::hms 中,否则会出现错误。
  2. 因为我个人发现辅助轴总是有点混乱,特别是辅助 x 轴和 y 轴,我根据线条的颜色为 x 和 y 标签着色。如果你不喜欢,你可以简单地删除 theme() adjustemnts。
library(ggplot2)
library(dplyr)

tw1_START <- "2008-01-01"; tw1_END <- "2010-01-01"
tw2_START <- "1990-01-01"; tw2_END <- "1992-01-01"
s_factor <- .52

Intv <- interval(ymd(tw2_START), ymd(tw1_START))
IntvM <-  time_length(Intv, "month") # time_length(YrDis , "year")


tw01 <- economics_long %>% 
  filter(variable== "pce" & date  > tw1_START  & date < tw1_END )

tw02 <- economics_long %>% 
  filter(variable== "pce" & date  > tw2_START  & date < tw2_END) %>% 
  mutate(date = date +  hms::hms(months(IntvM))) %>% 
  mutate(value01 = value01 + s_factor)


tw <- bind_rows(tw01, tw02, .id = "time_window")
tw %>% 
  ggplot(aes(date, value01, colour = time_window)) + 
  geom_line() + 
  scale_x_date(sec.axis = sec_axis(~ . -hms::hms(months(IntvM))))  + 
  scale_y_continuous(sec.axis = sec_axis(~ . - s_factor), position = "right") +
  theme(axis.text.x.top = element_text(color = scales::hue_pal()(2)[2]),
        axis.text.x.bottom = element_text(color = scales::hue_pal()(2)[1]),
        axis.text.y.right = element_text(color = scales::hue_pal()(2)[1]),
        axis.text.y.left = element_text(color = scales::hue_pal()(2)[2]))