我有一些時間序列資料,每小時,運行 5 年。我想用年份作為分組變數繪制我的時間序列資料,因此一年中的所有日期和時間都有 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,例如,因為我想要繪制每小時周期的復雜性)
uj5u.com熱心網友回復:
你需要一個通用的時間戳來在 x 軸上繪圖......所以plotDate通過將 dateTime 中的所有年份設定為 2000 年(或其他......)來創建一個 ( )
在創建 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")

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/371949.html
上一篇:如何在stat_function中按線型和顏色創建圖例
下一篇:將點分配到x軸上的特定范圍
