簡體   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