在geom_histogram

时间:2019-02-07 10:04:23

标签: r ggplot2

我有一个数据集,其中包含一天中特定时间发生的事件。我想对每小时的事件进行直方图绘制。我抬头一望 R - emulate the default behavior of hist() with ggplot2 for bin widthR hist vs geom_hist break points 到目前为止,这让我很伤心,但这仍然不是我想要的。我尝试过:

library(ggplot2)
set.seed(1)
df1 = data.frame(t=as.integer(rnorm(100, 25, 8)) / 2) %% 24
ggplot(data=df1, aes(x=t)) +
  geom_histogram(binwidth=1, colour="steelblue4", fill="steelblue") +
  stat_bin(binwidth = 1, aes(label=..count..), vjust=-0.5, geom = "text") +
  scale_x_continuous("Time",
    breaks=seq(0, 23, by=4),
    labels=c("00:00", "04:00", "08:00", "12:00", "16:00", "20:00")) +
  scale_y_continuous(breaks = 0:15)

并得到了这张图片:

Incorrect histogram

此直方图是1)不正确和2)没有显示我想要的。直方图给人的印象是在04:00(或前后)有两个事件。当我们查看数据时,我们看到在3.5(即03:30)和4.5(04:30)有一个事件。我真正想要的是显示[00:00,01:00),[01:00,02:00)... [23:00,24:00)范围内事件数量的直方图。 03:30的事件应分配给与04:30的事件不同的箱。另外,我希望直方图可以覆盖从00:00到24:00的整天。像这样的东西(photoshopped!):

Better histogram, manually adjusted

一致
Time <- cut(df1$t, breaks = 0:24, dig.lab = 4, right = FALSE) 
as.data.frame(table(Time))

      Time Freq
1    [0,1)    0
2    [1,2)    0
3    [2,3)    0
4    [3,4)    1
5    [4,5)    1
6    [5,6)    1
7    [6,7)    3
8    [7,8)    4
9    [8,9)    2
10  [9,10)    7
11 [10,11)   11
12 [11,12)    8
13 [12,13)   12
14 [13,14)   10
15 [14,15)   14
16 [15,16)    8
17 [16,17)    6
18 [17,18)    4
19 [18,19)    5
20 [19,20)    0
21 [20,21)    1
22 [21,22)    1
23 [22,23)    1
24 [23,24)    0

使用geom_histogram()完全可行吗?如果没有,我还应该使用什么?

1 个答案:

答案 0 :(得分:1)

一种解决方案可能是使用geom_col()而不是geom_histogram():

Time <- cut(df1$t, breaks = 0:24, dig.lab = 4, right = FALSE) 
ggplot(data=as.data.frame(table(Time)), aes(x=.5+0:23, y=Freq)) +
  geom_col(colour="steelblue4", fill="steelblue") +
  geom_text(aes(label=Freq), vjust=-0.5) +
  scale_x_continuous("Time",
    breaks=seq(0, 24, by=4),
    labels=c("00:00", "04:00", "08:00", "12:00", "16:00", "20:00", "24:00")) +
  scale_y_continuous("count", breaks = 0:15)

这将导致下图:

Histogram - possible solution

但是我承认这有点不雅致,因为它需要为图形生成一个单独的数据框。