我正在尝试 H.Wickham 在 R 书中的钻石数据集。在 x = 克拉的钻石的默认 geom_histogram 中,binwidth 为 0.5,但 bin 1 从 -0.25 开始,即使克拉的最低值为 0.2。为什么会这样?附上图片和代码作为上下文。谁能帮忙解释一下。谢谢。
##geom_histogram
geom_histogram(mapping=aes(x = carat),binwidth = 0.5)
summary(diamonds)
##dplyr to get count of cut[![enter image description here][1]][1]
diamonds %>%
count(cut_width(carat,0.5))
Run Code Online (Sandbox Code Playgroud)
这有帮助吗?
在 p1 中,第一个 bin 以 0 为中心。但是您希望 bin 的左侧以 0 - p2 开始。所以你必须告诉 ggplot 移动垃圾箱。您可以使用文档中讨论的boundaryorcenter参数来执行此操作。
library(ggplot2)
library(patchwork)
##geom_histogram
p1 <-
ggplot(diamonds)+
geom_histogram(mapping=aes(x = carat), binwidth = 0.5)+
ggtitle("p1 bars centred on bin boundaries")
p2 <-
ggplot(diamonds)+
geom_histogram(mapping=aes(x = carat), binwidth = 0.5, boundary = 0)+
ggtitle("p2 bars between bin boundaries")
p1+p2
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2020 年 5 月 25 日创建
cut_width对宇宙的物理定律一无所知,所以不知道carat应该是正的。让我们看看它为什么这样做。我目前正在使用ggplot2-3.2.1,因此某些行可能已在较新的版本中更新。
debugonce(cut_width)
cut_width(diamonds$carat, 0.5)
# debug: {
# x <- as.numeric(x)
# width <- as.numeric(width)
# ...truncated...
Run Code Online (Sandbox Code Playgroud)
逐步退出,直到定义了大多数辅助变量,然后
x_range
# [1] 0.20 5.01
boundary
# [1] 0.25
c(min_x, max_x)
# [1] -0.25 5.51
breaks
# [1] -0.25 0.25 0.75 1.25 1.75 2.25 2.75 3.25 3.75 4.25 4.75 5.25
Run Code Online (Sandbox Code Playgroud)
重要的是,我们知道数据范围从 0.2 到 5.01 ( x_range),boundary是一半width(根据代码),并且min_x由另一个辅助函数 确定find_origin。为什么这个函数认为 -0.25 是合理的第一个 bin 开始?代码对此不是很清楚(我会问作者)。
如果你想控制它,请添加boundary=:
levels(cut_width(diamonds$carat, 0.5))
# [1] "[-0.25,0.25]" "(0.25,0.75]" "(0.75,1.25]" "(1.25,1.75]" "(1.75,2.25]" "(2.25,2.75]" "(2.75,3.25]" "(3.25,3.75]"
# [9] "(3.75,4.25]" "(4.25,4.75]" "(4.75,5.25]"
levels(cut_width(diamonds$carat, 0.5, boundary=0))
# [1] "[0,0.5]" "(0.5,1]" "(1,1.5]" "(1.5,2]" "(2,2.5]" "(2.5,3]" "(3,3.5]" "(3.5,4]" "(4,4.5]" "(4.5,5]" "(5,5.5]"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
293 次 |
| 最近记录: |