我有一个数据集,其中包含列StartTime
(例如16:32:11
)和Date
,ID
等。
我想绘制一个图,其x轴上为小时(00:00:00, 01:00:00 .. 23:00:00)
,在y轴上为该小时内具有StartTime
的聚合条目的计数。>
如何绘制此图?首先,我需要用StartTime
隐藏as.POSIXct(strptime)
吗?
答案 0 :(得分:0)
您可以使用lubridate软件包从字符串中提取小时数,然后绘制直方图:
# simulate data
library(lubridate)
set.seed(123)
n <- 1000 # number of rows/observations
event_time <- seconds_to_period(seconds(seq(0, 24 * 60 * 60 - 1)))
start_time <- sample(sprintf('%02d:%02d:%02d', hour(event_time), minute(event_time), second(event_time)),
size = n,
replace = TRUE)
df <- data.frame(
start_time,
id = 1:n,
start_date = sample(seq(dmy("01/01/2017"), dmy("01/01/2018"), 1), n, replace = TRUE),
stringsAsFactors = FALSE)
# plot histogram of time distribution of events
head(df)
# start_time id start_date hour
# 1 06:54:06 1 2017-04-11 6
# 2 18:55:09 2 2017-08-06 18
# 3 09:48:55 3 2017-02-28 9
# 4 21:11:32 4 2017-11-09 21
# 5 22:34:16 5 2017-11-07 22
# 6 01:05:36 6 2017-06-24 1
df$hour <- hour(hms(df$start_time))
hist(df$hour, breaks = 24, xlim = c(0, 25))