繁体   English   中英

R ggplot dateTime 数据并使用年份作为分组变量

[英]R ggplot dateTime data and use year as grouping variable

我有一些时间序列数据,每小时一次,跨越 5 年。 我想 plot 我的时间序列数据以年份作为分组变量,因此一年中的所有日期和时间都有 5 行。 只需在 x 轴上绘制 dateTime 并使用lubridate::year(dateTime)作为aes中的分组/颜色,就可以形成一条长线,上面有 5 种不同的颜色。

粗略的示例数据;

require(data.table)
require(lubridate)
require(ggplot2)

# this is just 7 days of hourly data, over 3 separate years
dt <- data.table(date = c(seq(as.Date("2018-03-01"), as.Date("2018-03-07"),by="day"), seq(as.Date("2019-03-01"), as.Date("2019-03-07"),by="day"), seq(as.Date("2020-03-01"), as.Date("2020-03-07"),by="day")), hr = rep(1:24, 21))
dt[, value := sin(hr)*sample(1:3,1)]

dt[, dateTime := as.POSIXct(paste0(date," ",hr,":00:00"), format="%Y-%m-%d %H:%M")]

# the result should be an x-axis of 7 days/hours, with three lines for years. 
# the below is obviously not that
ggplot(dt, aes(x=dateTime,y=value,group=year(dateTime), colour=year(dateTime)))+
  geom_line()

我认为有一种方法可以将 posix 时间格式化为没有年份组件的月/日/时间,但它似乎只返回 NA。

(例如,ps 对按yday分组并不真正感兴趣,因为我希望绘制每小时周期的复杂性)

您需要一个用于在 x 轴上绘制的公共时间戳。所以通过将 dateTime 中的所有年份设置为 2000 年(或其他任何年份)来创建一个( plotDate
在为 x 轴创建标签时,只需在格式中省略虚拟年份值。

# create some variables to use for plotting
dt[, year := lubridate::year(dateTime)]
dt[, datePlot := update(dateTime, year = 2000)]

#now plot
ggplot(data = dt, aes(x = datePlot, y = value, group = year, color = as.factor(year))) +
  geom_line(size = 1) + 
  scale_x_datetime(breaks = "12 hours", 
                   labels = function(x) format(x, "%d %b %H:%M")) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) +
  labs(x = "dateTime", color = "year")

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM