我使用 ggplot 繪制了一個簡單的直方圖,而不使用 binwidth 屬性。但是,我想查看直方圖的 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()
如何查看此值?
謝謝
uj5u.com熱心網友回復:
這里有兩種方法。
ggplot_build創建一個串列物件。它的第一個成員有一個 data.framedata和。這些值之間的差異是 binwidth;xminxmax- 有了
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 包于 2022-02-15 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/427652.html
