r - 绘图图:在 R 中计数 x 小时
问题描述
我有一个包含列StartTime
(例如16:32:11
)和Date
、ID
等的数据集。
我想绘制一个图表,在 x 轴上是小时,在 y 轴上是在那个小时内(00:00:00, 01:00:00 .. 23:00:00)
具有 a 的聚合条目的计数。StartTime
如何绘制此图?首先我需要隐藏StartTime
withas.POSIXct(strptime)
吗?
解决方案
您可以使用 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))
推荐阅读
- python - 在python(jupyter)中复制一个变量/使用具有相同变量的不同函数
- excel - 单击单元格,通过链接图片显示数据范围
- gcc - 将 gcc-8.2.0 与 musl 静态链接的补丁
- kdb - (q/kdb+) 使用前一行的结果更新行
- php - Laravel - 如果查询为空,则返回不同的查询
- vb.net - 如何将 Linq 结果转换为数据表(使用数据表而不是上下文)
- cassandra - cassandra如何在sstable中组织价值
- javascript - 通过 getElementById().innerHTML 编辑 div 没有任何变化
- enterprise-architect - 如何在 Enterprise Architect 14 中更改现有表的所有者和表空间?
- sql-server - sql脚本仅获取与给定条件匹配的几行