使用 forecast::ggseasonplot 的多个变量的季节性图

Seasonal plots for multiple variables using forecast::ggseasonplot

我正在尝试为数据框 df 绘制季节性图,其中包含 2 个变量(value1value2)的时间序列数据:

df <- structure(list(date = structure(c(18292, 18321, 18352, 18382, 
18413, 18443, 18474, 18505, 18535, 18566, 18596, 18627, 18658, 
18686, 18717, 18747, 18778, 18808, 18839, 18870, 18900, 18931, 
18961, 18992), class = "Date"), value1 = c(-2.94, -40.61, -6.89, 
3.04, -3.5, 0.18, 6.79, 9.08, 9.35, 10.92, 20.53, 18.04, 24.6, 
154.6, 30.4, 32.1, 27.7, 32.1, 19.2, 25.4, 28, 26.9, 21.7, 20.9
), value2 = c(-12.66, 7.56, -1.36, -14.39, -16.18, 3.29, -0.69, 
-1.6, 13.47, 4.83, 4.56, 7.58, 28.7, 18.9, 39.1, 44, 52, 37.1, 
28.2, 32.7, 17.2, 20.4, 31.4, 19.5)), class = "data.frame", row.names = c(NA, 
-24L))

我们可以使用以下方法在一个图中绘制两个时间序列:

meltdf <- melt(df, id='date')
meltdf %>%
  ggplot(aes(x=date, y=value, colour=variable, group=variable)) +
        geom_point() +
        geom_line()

输出:

但我希望用ggseasonplot分别为value1value2画两幅图,每幅都类似于下面的图:

library(forecast)
ggseasonplot(AirPassengers, col=rainbow(12), year.labels=TRUE)

我遇到的问题是how to convert each subset dataframe to ts objects:

meltdf %>%
  filter(variable=='value1') %>% 
  as.ts() %>% 
  ggseasonplot(col=rainbow(12), year.labels=TRUE)

谢谢。

更新: 仅使用 ggplot2 实现:

meltdf %>% 
  filter(variable=='value2') %>% 
  select(-variable) %>% 
  mutate(
    year = factor(year(date)),     # use year to define separate curves
    date = update(date, year = 1)  # use a constant year for the x-axis
  ) %>% 
  ggplot(aes(date, value, color = year)) +
    scale_x_date(date_breaks = "1 month", date_labels = "%b")+
  geom_line()+
  geom_point()

这就是 feasts 包的用途 -- 处理同一数据框中包含多个序列的时间序列图形。以下是使用提供的示例数据执行此操作的方法。

library(tsibble)
library(feasts)
library(tidyr)
library(dplyr)

# Convert to tsibble object and plot using gg_season()
df %>%
  pivot_longer(value1:value2) %>%
  mutate(date = yearmonth(date)) %>%
  as_tsibble(index = date, key = name) %>%
  gg_season(value)

reprex package (v2.0.1)

创建于 2022-02-14

有关更多示例,请参阅 https://otexts.com/fpp3/seasonal-plots.html