在 ggplot 直方图中使用 Hour:Minute 更改 bin 大小

Changing Bin Sizes Using Hour:Minute In ggplot histogram

我正在创建某事发生时间的直方图,因此 x 轴是 hour:minute 格式的时间。我正在尝试将 bins 更改为 15 分钟而不是 5 分钟,但我无法这样做。 geom_histogram 中的 binwidth 参数似乎没有响应。在处理 H:M 时有没有办法改变 bin 大小?如果不是,我可以将分钟表示为小时的百分比,例如,9:45 AM 将是 9.75,但我更愿意保留 hour:min 格式。谢谢。

下面的代码将重现直方图。

temp <- structure(list(unique.data.Date. = structure(c(14615, 14616, 
14617, 14622, 14623, 14635, 14636, 14637, 14642, 14650, 14651, 
14658, 14659, 14662, 14663, 14671, 14672, 14677, 14679, 14683
), class = "Date"), Time = structure(c(2L, 16L, 11L, 9L, 3L, 
8L, 2L, 2L, 3L, 1L, 9L, 2L, 16L, 3L, 4L, 52L, 13L, 8L, 17L, 4L
), .Label = c("09:35", "09:40", "09:45", "09:50", "09:55", "10:00", 
"10:05", "10:10", "10:15", "10:20", "10:25", "10:30", "10:35", 
"10:40", "10:45", "10:50", "10:55", "11:00", "11:05", "11:10", 
"11:15", "11:20", "11:25", "11:30", "11:35", "11:40", "11:45", 
"11:55", "12:00", "12:05", "12:10", "12:15", "12:20", "12:30", 
"12:35", "12:40", "12:45", "12:50", "13:00", "13:15", "13:20", 
"13:30", "13:40", "13:45", "14:05", "14:10", "14:15", "14:20", 
"14:35", "14:40", "14:45", "14:50", "15:20", "15:25", "15:30", 
"15:35", "15:45", "15:50", "16:00"), class = "factor")), .Names = c("unique.data.Date.", 
"Time"), row.names = c(NA, 20L), class = "data.frame")

ggplot(temp, aes(x=temp$Time)) + 
  geom_histogram(aes(stat="bin"), fill="lightblue", binwidth = 50, color="grey50")

这是您所期望的吗:

 ggplot(temp, aes(x=as.POSIXct(temp$Time,format="%H:%M"))) + 
    geom_histogram( fill="lightblue", binwidth = 15*60,  # 15 min *60 sec/min
                color="grey50")

请注意,这些 "times" 都在不同的日期,但是转换为 POSIXct 格式将隐含地使所有日期都为今天的日期,因此在原始日期中进行转换可能不是一个好主意数据框。