如何验证垃圾箱的总面积是否为1?

How to verify if the total area of the bins is 1?

我使用下面的代码来获取直方图。

plt <- ggplot(iris, aes(x = Sepal.Length)) +
    geom_histogram(aes(y = ..density..))

我不确定我从这段代码中得到了什么。我认为函数 geom_histogram() 中的密度选项用于获取直方图是密度分布,但我如何验证这一点? NA 是如何处理的?谢谢

如何验证 bin 的面积总和为 1

从直方图开始:

library(ggplot2)
library(tidyverse)

p <- iris %>% 
  ggplot(aes(x = Sepal.Length)) +
  geom_histogram(aes(y = ..density..))

Deconstruct the ggplot查看原始数据:

pp <- ggplot_build(p)

# View all data
pp$data

获取计算条形下面积所需的数据:

heights_of_bars <- pp$data[[1]]$y

#  [1] 0.2148148 0.0537037 0.2148148 0.1074074 0.5907407
#  [6] 0.5370370 0.4833333 0.2148148 0.3759259 0.3759259
# [11] 0.3222222 0.4296296 0.3759259 0.4833333 0.3222222
# [16] 0.2148148 0.4833333 0.6444444 0.1074074 0.4296296
# [21] 0.1611111 0.2685185 0.0537037 0.1611111 0.0537037
# [26] 0.0537037 0.0537037 0.2148148 0.0000000 0.0537037

number_of_bins <- nrow(pp$data[[1]])
# [1] 30 

x_distance <- last(pp$data[[1]]$xmax) - first(pp$data[[1]]$xmin)
# [1] [1] 3.724138

width_of_bin <- x_distance * (1/number_of_bins)
# [1] 0.1241379

并计算总面积:

sum(heights_of_bars * width_of_bin)
# [1] 1