如何在一个图中简单地绘制不同年份的相似日期
how to simply plot similar dates of different years in one plot
我有一个带日期的数据框。这是前 3 行 dput
:
df.cv <- structure(list(ds = structure(c(1448064000, 1448150400, 1448236800
), class = c("POSIXct", "POSIXt"), tzone = "UTC"), y = c(10.4885204292416,
10.456538985014, 10.4264986311659), yhat = c(10.4851491194439,
10.282089547027, 10.4354960430083), yhat_lower = c(10.4169914076864,
10.2162549984153, 10.368531352493), yhat_upper = c(10.5506038959764,
10.3556867861042, 10.5093092789713), cutoff = structure(c(1447977600,
1447977600, 1447977600), class = c("POSIXct", "POSIXt"), tzone = "UTC")),.Names = c("ds",
"y", "yhat", "yhat_lower", "yhat_upper", "cutoff"), row.names = c(NA,
-3L), class = c("`enter code here`tbl_df", "tbl", "data.frame"))
我试图用 ggplot + geom_line
从一个图中的相似 day/month 组合中绘制数据。因此,例如,我希望 2016-01-01 的 y 值出现在与 2017-01-01 相同的 x 值上。如果找到一种方法来做到这一点,但它似乎是一个非常复杂的解决方法:
library(tidyverse)
library(lubridate)
p <- df.cv %>%
mutate(jaar = as.factor(year(ds))) %>%
mutate(x = as_date(as.POSIXct(
ifelse(jaar==2016, ds + years(1), ds),
origin = "1970-01-01")))
ggplot(p %>% filter(jaar!=2015), aes(x=x, group=jaar, color=jaar)) +
geom_line(aes(y=y))
有效,但如您所见,我首先必须提取年份,然后使用 ifelse
将一年仅添加到 2016 年日期,使用 POSIXct
进行转换,因为 ifelse
剥离 class,转换回 POSIXct
,同时提供 origin
,最后用 as_date
.
删除时间戳
难道没有更简单、更优雅的方法吗?
使用year<-
将年份替换为任意固定闰年:
p <- df.cv %>%
mutate(jaar = as.factor(year(ds)),
x = `year<-`(as_date(ds), 2000))
ggplot(p, aes(x = x, y = y, color = jaar)) +
geom_line()
我有一个带日期的数据框。这是前 3 行 dput
:
df.cv <- structure(list(ds = structure(c(1448064000, 1448150400, 1448236800
), class = c("POSIXct", "POSIXt"), tzone = "UTC"), y = c(10.4885204292416,
10.456538985014, 10.4264986311659), yhat = c(10.4851491194439,
10.282089547027, 10.4354960430083), yhat_lower = c(10.4169914076864,
10.2162549984153, 10.368531352493), yhat_upper = c(10.5506038959764,
10.3556867861042, 10.5093092789713), cutoff = structure(c(1447977600,
1447977600, 1447977600), class = c("POSIXct", "POSIXt"), tzone = "UTC")),.Names = c("ds",
"y", "yhat", "yhat_lower", "yhat_upper", "cutoff"), row.names = c(NA,
-3L), class = c("`enter code here`tbl_df", "tbl", "data.frame"))
我试图用 ggplot + geom_line
从一个图中的相似 day/month 组合中绘制数据。因此,例如,我希望 2016-01-01 的 y 值出现在与 2017-01-01 相同的 x 值上。如果找到一种方法来做到这一点,但它似乎是一个非常复杂的解决方法:
library(tidyverse)
library(lubridate)
p <- df.cv %>%
mutate(jaar = as.factor(year(ds))) %>%
mutate(x = as_date(as.POSIXct(
ifelse(jaar==2016, ds + years(1), ds),
origin = "1970-01-01")))
ggplot(p %>% filter(jaar!=2015), aes(x=x, group=jaar, color=jaar)) +
geom_line(aes(y=y))
有效,但如您所见,我首先必须提取年份,然后使用 ifelse
将一年仅添加到 2016 年日期,使用 POSIXct
进行转换,因为 ifelse
剥离 class,转换回 POSIXct
,同时提供 origin
,最后用 as_date
.
难道没有更简单、更优雅的方法吗?
使用year<-
将年份替换为任意固定闰年:
p <- df.cv %>%
mutate(jaar = as.factor(year(ds)),
x = `year<-`(as_date(ds), 2000))
ggplot(p, aes(x = x, y = y, color = jaar)) +
geom_line()