R中的季节图

Season plot in R

我有一个包含日期和平均值的数据集,如下所示:

Dates AVG
2019-04-01 29.2
2019-08-01 29.5
2020-12-01 15.6
2019-02-01 28.7
2020-01-01 16.3
2019-07-01 29.6

日期列是字符,所以我使用了:

library(lubridate)
my_data$Dates <- ymd(my_data$Dates)

所以,现在我的数据集的 Dates 列具有日期格式,AVG 具有数字格式。 我想做一个散点图,它将分别连接每年 AVG 的点。所以,我想为 2019 年设计一条线,为 2020 年设计一条不同的线,但在同一个情节中。

我在网上看到我可以做类似的事情,如果我使用预测库的 ggseasonplot,但是这个命令 excpect 你有 xts 数据,在我的例子中只有第一列是日期格式。 我尝试使用以下方法将整个数据集转换为 xts 数据集:

library(xts)
xts_data <- as.xts(my_data)

但我收到以下错误,因为我的数据不是 POSIXlt 格式:

Error in as.POSIXlt.character(x, tz, ...) : 
  character string is not in a standard unambiguous format

我不知道如何使我的数据以正确的格式使用 ggseasonplot。对此的任何帮助将不胜感激。 此外,任何其他关于以另一种方式完成我想要的情节的建议(根本不使用 ggseasonplot),也将不胜感激。

提前致谢!

您可能会对 ggplot2 感兴趣,一旦您习惯了它的语法和逻辑,它可以很快给出漂亮的情节。

要使用 ggplot2 获取 ggseasonplot 的输出,您可以使用 lubridate 中的函数,例如 month,获取您的 x 坐标和 year, 对每年的观察结果进行分组。

library(ggplot2)

ggplot(data = my_data, 
             mapping = aes(x = month(Dates, label = TRUE), 
                           y = AVG))+
  geom_point()+
  geom_line(aes(group = factor(year(Dates)),
                color = factor(year(Dates))))+
  scale_color_discrete(name = "Year")+
  xlab(label = "Month")

如果要显示没有数据的月份:

ggplot(data = my_data, 
             mapping = aes(x = month(Dates, label = TRUE), 
                           y = AVG))+
  geom_blank(data=data.frame(),
             aes(x = month(seq(ymd('2020-01-01'),
                           ymd('2020-12-01'), 
                           by = '1 month'),
                       label = TRUE),
                 y = NULL))+
  geom_point()+
  geom_line(aes(group = factor(year(Dates)),
                color = factor(year(Dates))))+
  scale_color_discrete(name = "Year")+
  xlab(label = "Month")

原始数据

my_data <- read.table(header = TRUE,
             text="Dates    AVG
             2019-04-01     29.2
             2019-08-01     29.5
             2020-12-01     15.6
             2019-02-01     28.7
             2020-01-01     16.3
             2019-07-01     29.6")