r - 如何在 R 中以日期和时间为 x 轴进行绘图
问题描述
大家好,我一直在尝试绘制一些数据,其中 x 轴是某一天的时间,y 轴是某个路段的自由流动速度的数值。我的部分数据的一个简单示例如下所示
> mydf1
# A tibble: 11 x 3
Date_UTC Time Free_Flow_Speed
<date> <chr> <dbl>
1 2019-05-07 08:15:00 81.0
2 2019-05-07 08:30:00 9.36
3 2019-05-07 08:45:00 4.15
4 2019-05-07 09:00:00 7.18
5 2019-05-07 09:15:00 9.78
6 2019-05-07 09:30:00 16.4
7 2019-05-07 09:45:00 97.9
8 2019-05-07 10:00:00 101.
9 2019-05-07 10:15:00 101.
10 2019-05-07 10:30:00 102.
11 2019-05-07 10:45:00 100.
我通过使用转换“Date_UTC”创建了“时间”
mydf1$Time <- format(as.POSIXct(data2$`UTC Date and Time`), format = "%H:%M:%S")
我试图在 x 轴上绘制“时间”,在 y 轴上绘制“Free_Flow_Speed”:
> plot(mydf1$Time, mydf1$Free_Flow_Speed)
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
2: In min(x) : no non-missing arguments to min; returning Inf
3: In max(x) : no non-missing arguments to max; returning -Inf
我试图四处调查,显然,时间被转换为“NAs”,可能是因为“时间”是“字符”而“Free_Flow_Speed”是“双/数字”
> str(mydf1)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 11 obs. of 3 variables:
$ Date_UTC : Date, format: "2019-05-07" "2019-05-07" "2019-05-07" "2019-05-07" ...
$ Time : chr "08:15:00" "08:30:00" "08:45:00" "09:00:00" ...
$ Free_Flow_Speed: num 80.99 9.36 4.15 7.18 9.78 ...
我试图将“Free_Flow_Speed”转换为“Char”但无济于事。
>mydf1 <- as.numeric(as.character(mydf1$Free_Flow_Speed))
Error in mydf1$Free_Flow_Speed : $ operator is invalid for atomic vectors
> mydf2 <- c(mydf1$Time, as.numeric(as.character(mydf1$Free_Flow_Speed)))
输入(数据)
> dput(mydf1)
structure(list(Date_UTC = structure(c(18023, 18023, 18023, 18023,
18023, 18023, 18023, 18023, 18023, 18023, 18023), class = "Date"),
Time = c("08:15:00", "08:30:00", "08:45:00", "09:00:00",
"09:15:00", "09:30:00", "09:45:00", "10:00:00", "10:15:00",
"10:30:00", "10:45:00"), Free_Flow_Speed = c(80.99, 9.36,
4.15, 7.18, 9.78, 16.37, 97.91, 100.54, 100.81, 102.46, 100.27
)), row.names = c(NA, -11L), class = c("tbl_df", "tbl", "data.frame"
))
如果有人可以阐明如何使用“时代”进行绘图,我会很高兴。在 excel 中这是可行的,但我正在尝试使用这个数据集探索 ggplot2,并且希望能够意识到我做错了什么。
提前致谢!
解决方案
你的线
mydf1$Time <- format(as.POSIXct(data2$`UTC Date and Time`), format = "%H:%M:%S")
尤其
data2$`UTC Date and Time`
与您提供的输入数据不对应。
可以通过首先将日期和小时粘贴在一起然后转换来实现正确的转换:
df1 <- df1 %>% mutate(all_date=as.POSIXct(paste(Date_UTC,Time),format = "%Y-%m-%d %H:%M:%S"))
最后只是绘制它:
plot(df1$all_date,df1$Free_Flow_Speed)