我有一个数据框,其中一列包含不同的日期,包括时间,例如
as.POSIXct(c("2017-07-03 08:23:00",
"2017-07-03 09:00:00",
"2017-07-03 17:23:00",
"2017-07-03 18:05:00",
"2017-07-04 08:24:00",
"2017-07-04 09:02:00",
"2017-07-04 17:24:00",
"2017-07-04 18:01:00",
"2017-07-05 08:57:00",
"2017-07-05 09:31:00",
"2017-07-05 16:25:00",
"2017-07-05 17:14:00"))
现在我想看一下某个时间间隔发生的次数(比如15分钟)。因此,我的目标是获得频率(所有天数)与一天中的时间的直方图。
任何提示?
编辑:我试图通过
提取时间df$Time <- hm(format(df$Date, "%H:%M"))
但这给我留下了一段我不知道如何处理的课时。我也试过像
这样的东西ggplot(df, aes(Date)) +
geom_histogram() +
scale_x_time()
我的主要问题是如何使用ggplot进行绘图。
答案 0 :(得分:2)
这可能是一种更简单的方法,但这是我的方法......
library(plyr)
library(lubridate)
#Sample Data
df<-data.frame(time=as.POSIXct(c(
'2017-07-03 08:23:00',
'2017-07-03 09:00:00',
'2017-07-03 17:23:00',
'2017-07-03 18:05:00',
'2017-07-04 08:24:00',
'2017-07-04 09:02:00',
'2017-07-04 17:24:00',
'2017-07-04 18:01:00',
'2017-07-05 08:57:00',
'2017-07-05 09:31:00',
'2017-07-05 16:25:00',
'2017-07-05 17:14:00')))
#Extract Time
df$hour = hour(df$time) + minute(df$time)/60 + second(df$time)/3600
#Create Bins
bins=c(paste0(rep(c(paste0(0,0:9),10:23), each=4),".", c("00",25,50,75))[-1],"24:00")
#Divide Data Into Bins
df$bins = cut(df$hour, breaks=seq(0, 24, 0.25), labels=bins)
#Reformat to Numeric
df$bins <- as.numeric(as.character(df$bins))
#Histogram
hist(df$bins)
#With ggplot
library(ggplot2)
ggplot(df, aes(bins)) +
geom_histogram()