R 如何简单地在一个图中绘制不同年份的相似日期
我有一个带有日期的数据框。以下是带有R 如何简单地在一个图中绘制不同年份的相似日期,r,date,ggplot2,lubridate,R,Date,Ggplot2,Lubridate,我有一个带有日期的数据框。以下是带有dput的前3行: 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,
dput
的前3行:
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"))
它是有效的,但正如您所看到的,我首先必须提取年份,然后使用ifelse
将一年仅添加到2016年的日期,使用POSIXct
进行转换,因为ifelse
剥离类,在提供原点的同时将其转换回POSIXct
,最后删除带有的时间戳作为\u date
有没有一种更简单、更优雅的方法可以做到这一点?使用year其他一些替代方法:,啊,太好了!去年我看到了《代码》
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))
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()