R - 如何创建季节性情节 - 多年不同的线条

Ess*_*ssi 3 r time-series ggplot2

我昨天已经问了同样的问题,但直到现在我还没有得到任何建议,所以我决定删除旧的,然后再问,给予额外的信息.

再来一次:

我有这样的数据帧:

链接到原始数据框:https://megastore.uni-augsburg.de/get/JVu_V51GvQ/

      Date   DENI011
1 1993-01-01   9.946
2 1993-01-02  13.663
3 1993-01-03   6.502
4 1993-01-04   6.031
5 1993-01-05  15.241
6 1993-01-06   6.561
     ....
     ....
6569 2010-12-26  44.113
6570 2010-12-27  34.764
6571 2010-12-28  51.659
6572 2010-12-29  28.259
6573 2010-12-30  19.512
6574 2010-12-31  30.231
Run Code Online (Sandbox Code Playgroud)

我想创建一个图表,使我能够比较多年来DENI011中的月度值.所以我想要这样的东西:

http://r-statistics.co/Top50-Ggplot2-Visualizations-MasterList-R-Code.html#Seasonal%20Plot 在此输入图像描述

1月至12月的x尺度,y尺度的值和不同颜色线显示的年份.

我在这里发现了几个类似的问题,但对我来说没什么用.我试图按照网站上的说明进行示例,但问题是我无法创建一个ts对象.

然后我这样试了:

Ref_Data$MonthN <- as.numeric(format(as.Date(Ref_Data$Date),"%m")) # Month's number
Ref_Data$YearN <- as.numeric(format(as.Date(Ref_Data$Date),"%Y"))
Ref_Data$Month  <- months(as.Date(Ref_Data$Date), abbreviate=TRUE) # Month's abbr.

g <- ggplot(data = Ref_Data, aes(x = MonthN, y = DENI011, group = YearN, colour=YearN)) + 
  geom_line() +
  scale_x_discrete(breaks = Ref_Data$MonthN, labels = Ref_Data$Month)
Run Code Online (Sandbox Code Playgroud)

这也没有用,情节看起来很糟糕.从1993年到2010年,我不需要将所有年份都放在1个地块中.实际上只有几年就可以了,比如1998-2006.

和建议,如何解决这个问题?

Mik*_*ila 9

正如其他人所指出的那样,为了创建一个例如您用作示例的图,您必须首先聚合您的数据.但是,也可以在类似的情节中保留每日数据.

reprex::reprex_info()
#> Created by the reprex package v0.1.1.9000 on 2018-02-11

library(tidyverse)
library(lubridate)

# Import the data
url <- "https://megastore.uni-augsburg.de/get/JVu_V51GvQ/"
raw <- read.table(url, stringsAsFactors = FALSE)

# Parse the dates, and use lower case names
df <- as_tibble(raw) %>% 
  rename_all(tolower) %>% 
  mutate(date = ymd(date))
Run Code Online (Sandbox Code Playgroud)

实现此目的的一个技巧是将日期变量中的年份组件设置为常量,有效地将日期折叠为一年,然后控制轴标签,以便您不在绘图中包含常量年份.

# Define the plot
p <- df %>% 
  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, deni011, color = year)) +
    scale_x_date(date_breaks = "1 month", date_labels = "%b")

# Raw daily data
p + geom_line()
Run Code Online (Sandbox Code Playgroud)

在这种情况下,你的日常数据变化很大,所以这有点乱.您可以在一年内磨练,以便更好地了解每日变化.

# Hone in on a single year
p + geom_line(aes(group = year), color = "black", alpha = 0.1) +
  geom_line(data = function(x) filter(x, year == 2010), size = 1)
Run Code Online (Sandbox Code Playgroud)

但最终,如果你想要一次看几年,那么提出平滑的线条而不是原始的每日价值可能是一个好主意.或者,确实是一些月度汇总.

# Smoothed version
p + geom_smooth(se = F)
#> `geom_smooth()` using method = 'loess'
#> Warning: Removed 117 rows containing non-finite values (stat_smooth).
Run Code Online (Sandbox Code Playgroud)