我正在嘗試為 dataframe 繪制季節性圖df,其中包含 2 個變數(value1和value2)的時間序列資料:
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分別繪制兩個圖value1,value2每個圖都類似于以下圖:
library(forecast)
ggseasonplot(AirPassengers, col=rainbow(12), year.labels=TRUE)

我遇到的問題是如何將每個子集資料幀轉換為 ts 物件:
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()

uj5u.com熱心網友回復:
這就是這個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 包于 2022-02-14 創建(v2.0.1)
有關更多示例,請參見https://otexts.com/fpp3/seasonal-plots.html。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/427662.html
標籤:r ggplot2 时间序列 ggseasonplot
上一篇:如何在我的條形圖中覆寫單個資料點
下一篇:創建GGPLOT直方圖
