gpt4 book ai didi

r - 查找使用 ggplot2 绘制的直方图的 binwidth

转载 作者:行者123 更新时间:2023-12-05 05:46:41 28 4
gpt4 key购买 nike

我在没有使用 binwidth 属性的情况下使用 ggplot 绘制了一个简单的直方图。但是,我想查看直方图的 binwidth 值。

set.seed(1234)
df <- data.frame(
sex=factor(rep(c("F", "M"), each=200)),
weight=round(c(rnorm(200, mean=55, sd=5), rnorm(200, mean=65, sd=5)))
)
head(df)

library(ggplot2)

ggplot(df, aes(x=weight)) + geom_histogram()

如何查看这个值?

谢谢

最佳答案

这里有两种方式。

  1. 使用ggplot_build 创建一个列表对象。它的第一个成员有一个带有 xminxmax 的 data.frame data。这些值之间的差异是 binwidth;
  2. 有了layer_data,上面的过程就更直接了。它提取data.frame,其余相同。

由于浮点精度问题,unique 的返回值不是长度为 1 的向量。可以使用任何值。

set.seed(1234)
df <- data.frame(
sex=factor(rep(c("F", "M"), each=200)),
weight=round(c(rnorm(200, mean=55, sd=5), rnorm(200, mean=65, sd=5)))
)

library(ggplot2)

gg <- ggplot(df, aes(x=weight)) + geom_histogram()

gg_build <- ggplot_build(gg)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
bin_width <- gg_build$data[[1]]$xmax - gg_build$data[[1]]$xmin
unique(bin_width)
#> [1] 1.344828 1.344828 1.344828

diff(range(df$weight))/30
#> [1] 1.3

gg_data <- layer_data(gg)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
unique(gg_data$xmax - gg_data$xmin)
#> [1] 1.344828 1.344828 1.344828

bw <- unique(gg_data$xmax - gg_data$xmin)[1]
bw
#> [1] 1.344828

reprex package 创建于 2022-02-15 (v2.0.1)

关于r - 查找使用 ggplot2 绘制的直方图的 binwidth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71125723/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com