首页 > 解决方案 > geom_histogram、分数/有界数据和边界参数

问题描述

我想绘制一些小数 [0,1] 有界的数据。中的默认设置geom_histogram()并不好:

library(tidyverse)

set.seed(1)
d = tibble(
  x = runif(1000)
)

#plot 1
ggplot(d, aes(x)) +
  geom_histogram()
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

所以在这里我们看到末端条的高度较低,因为它们覆盖了可能数据范围之外的范围。我们可以尝试用看起来应该可以工作的边界来解决这个问题。从文档

中心,边界:bin 位置说明符。对于单个图,只能指定一个,中心或边界。center 指定其中一个 bin 的中心。边界指定两个 bin 之间的边界。请注意,如果其中一个高于或低于数据范围,则事物将移动适当的 binwidth 整数倍。例如,要以整数为中心使用 binwidth = 1 和 center = 0,即使 0 超出数据范围。或者,可以使用 binwidth = 1 和边界 = 0.5 指定相同的对齐方式,即使 0.5 超出数据范围。

#plot 2
ggplot(d, aes(x)) +
  geom_histogram(boundary = 0)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

它适用于左侧,但奇怪的是右侧现在有一个完全超出范围的块。那里没有任何数据。诡异的。所以这一定意味着最后一个默认柱线开始时非常接近 1,这再次意味着默认出价宽度必须有一些奇数值。该图显示有 30 个 bin,因此 binwidth 必须为 1/30。我们也可以尝试设置closed参数,以防万一:

#plot 3
ggplot(d, aes(x)) +
  geom_histogram(boundary = 0, closed = "left")
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

#plot 4
ggplot(d, aes(x)) +
  geom_histogram(boundary = 0, closed = "right")
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

#plot 5
ggplot(d, aes(x)) +
  geom_histogram(boundary = 0, binwidth = 1/30)

手动设置binwidth可以解决问题,但这是为什么呢?

reprex 包于 2021-06-23 创建 (v2.0.0 )

标签: rggplot2histogram

解决方案


推荐阅读