使用小时更改仓大小:分钟在ggplot直方图中

时间:2015-03-22 18:47:54

标签: r time ggplot2 histogram

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

enter image description here

以下代码将重现直方图。

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")

1 个答案:

答案 0 :(得分:2)

这是你所期望的:

 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")

enter image description here

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