首页 > 解决方案 > 绘图图:在 R 中计数 x 小时

问题描述

我有一个包含列StartTime(例如16:32:11)和DateID等的数据集。

我想绘制一个图表,在 x 轴上是小时,在 y 轴上是在那个小时内(00:00:00, 01:00:00 .. 23:00:00)具有 a 的聚合条目的计数。StartTime

如何绘制此图?首先我需要隐藏StartTimewithas.POSIXct(strptime)吗?

标签: rplot

解决方案


您可以使用 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)) 

输出: 活动分布


推荐阅读