[英]How to plot with date and time as x-axis in R
大家好,我一直在尝试绘制一些数据,其中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
我尝试研究一下,很显然,时间被转换为仅“ NA”,可能是因为“时间”为“字符”,而“ 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(数据)
> 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.