更改密度直方图的 binwidth 以使概率总和为 1

Car*_*cus 5 r histogram ggplot2

我已经发现了很多问题,但不知何故它并没有真正帮助我。我不明白如何更改 ggplot2 中密度直方图中的 binwidth,以便概率总和为 1。似乎只有当 binwidth 恰好为 1 时它才有效。这是一个示例:

set.seed(1)
df = data.frame("data" = runif(1000, min=0, max=100))

a = ggplot(data = df, aes(x = data))+  
    geom_histogram(aes(y=..density..),colour="black", fill = "white", 
    breaks=seq(0, 100, by = 50)) 


b = ggplot(data = df, aes(x = data))+  
    geom_histogram(aes(y =..density..), 
             breaks=seq(0, 100, by = 30), 
             col="black", 
             fill="white") 
c = ggplot(data = df, aes(x = data))+  
    geom_histogram(aes(y =..density..), 
             breaks=seq(0, 100, by = 10), 
             col="black", 
             fill="white")

d = ggplot(data = df, aes(x = data))+  
    geom_histogram(aes(y =..density..), 
             breaks=seq(0, 100, by = 1), 
             col="black", 
             fill="white") 

grid.arrange(a,b,c,d, ncol= 2)
Run Code Online (Sandbox Code Playgroud)

如果你看一下概率轴,你会发现前三张图一定是错误的。这些不是正确的直方图,因为箱的总和不等于 1。根据直方图 a、b、c 或 d,y 轴甚至没有显着变化。我还尝试用“binwidth”命令替换“breaks”命令,但情况更糟。我还想知道如何计算直方图的单个 bin 的概率来证明它的总和是否为 1?

谢谢你的帮助。

Ant*_*osK 2

模拟一些数据:

library(ggplot2)
library(dplyr)

set.seed(1)
df = data.frame("data" = runif(1000, min=0, max=100))
Run Code Online (Sandbox Code Playgroud)

您可以获得的第一个图是:

# y axis has the density estimate values 
ggplot(data = df, aes(x = data))+  
  geom_histogram(aes(y=..density..),colour="black", fill = "white", 
                 breaks=seq(0, 100, by = 50))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

该图的 y 轴上有密度估计值。这些值对应于密度图,而不是您创建的条形图。您可以看到这个版本,其中密度图被覆盖:

# y axis has the density estimate values and the density plot
ggplot(data = df, aes(x = data))+  
  geom_histogram(aes(y=..density..),colour="black", fill = "white", 
                 breaks=seq(0, 100, by = 50)) +
  geom_density(aes(data), col="red")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 解释这一点的一种方法是,红线上的每个点都有一个被选择的概率,并且位于 y 轴上(即很多点意味着概率趋于接近于零)。

你可以用这个得到你想要的:

# y axis has the probabilities of each bar (bar counts / all counts)
ggplot(data = df, aes(x = data))+  
  geom_histogram(aes(y=..count../sum(..count..)),colour="black", fill = "white", 
                 breaks=seq(0, 100, by = 50)) 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

执行上述操作的另一种方法是,同时保留数据(以供将来使用或仅检查概率总和为 1):

# assign the breaks
breaks = cut(df$data, seq(0, 100, by = 50))

# count observations in each bar and probability of each bar
df %>%
  mutate(Breaks = breaks) %>%
  count(Breaks) %>%
  mutate(Prc = n/sum(n))

# # A tibble: 2 x 3
#     Breaks     n   Prc
#     <fctr> <int> <dbl>
# 1   (0,50]   520  0.52
# 2 (50,100]   480  0.48

# plot the above
df %>%
  mutate(Breaks = breaks) %>%
  count(Breaks) %>%
  mutate(Prc = n/sum(n)) %>%
  ggplot(aes(Breaks, Prc)) + geom_col()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述