在水平轴上用日时间绘制时间序列

时间:2018-09-01 22:49:02

标签: r time-series

您好,我有一些工作代码可以从单个站点中选择数据并将其绘制为时间序列。在该数据中,该数据是以下格式的日期时间:

28 11AC068 2018-08-30T02:15:00-06:00
29 11AC068 2018-08-30T02:20:00-06:00

file = "http://dd.weather.gc.ca/hydrometric/csv/SK/hourly/SK_hourly_hydrometric.csv"
skdat <- read.csv(file, head=T, sep=",", dec=".")
skdate <- skdat 
colnames(skdat) <- c("ID", "Date", "Water.Level", "Grade.1", "Symbol.1", 
                     "QA/QC-1", "Discharge/Debit", "Grade.2", "Symbol.2", 
                     "QA/QC-2")

#There are 151 Factors of ID
str(skdat$ID)
skdat$Date <- as.Date(skdat$Date, "%h/%m")
#"05AH050","05EF001"#,..: 151 151 151 151 151 151 151 151 151 151 ...
plot.ts(subset(skdat,  skdat$ID=='05EF001')$Water.Level, main="Plot TS of ID = 05EF001")
axis.Date(1, at=seq(min(skdat$Date), max(skdat$Date), by="hour"), format="%h-%m")

在子集中,日期时间被滤除了,是否有任何方法可以将该列保留在数据中,并用它来绘制水平轴,就像小时最小值一样?

1 个答案:

答案 0 :(得分:2)

您可以尝试类似的方法。

library(tidyverse)

file = "http://dd.weather.gc.ca/hydrometric/csv/SK/hourly/SK_hourly_hydrometric.csv"
skdat <- read.csv(file, head=T, sep=",", dec=".", stringsAsFactors = F)
colnames(skdat) <- c("ID", "Date", "Water.Level", "Grade.1", "Symbol.1", 
                     "QA/QC-1", "Discharge/Debit", "Grade.2", "Symbol.2", 
                     "QA/QC-2")

skdat %>% filter(ID=='05EF001') %>% 
  mutate(Date = gsub("-06:00$", "", Date) %>% lubridate::parse_date_time(., orders = "ymd HMS")) %>%
  ggplot(aes(Date, Water.Level))+
  geom_line()+
  scale_x_datetime(breaks = "4 hours", date_labels = "%H:%M")

reprex package(v0.2.0)于2018-09-01创建。