如何动态设置直方图binwidth

How to dynamically set histogram binwidth

我是一个完全的 R 菜鸟,正在学习 ggplot。 我不明白为什么第一个片段有效而第二个片段无效。我想在不猜测的情况下找到一个好的binwidth,所以我尝试了一个没有成功的实验。

library(ggplot2)
attach(diamonds)
d <- diamonds
x <- ggplot(d, aes(x = price))
x <- x + geom_histogram(binwidth = 50)
x
# worked fine, but using the sequence and substituting i didn't
i <- seq(1, 101, by = 10)  #tried to avoid the first arg as zero, but didn't work
x <- ggplot(d, aes(x = price))
x <- x + geom_histogram(binwidth = i) 
x

第二个抛出错误

Error in seq.default(round_any(range[1], size, floor), round_any(range[2],  : 
  'from' must be of length 1
Error in exists(name, envir = env, mode = mode) : 
  argument "env" is missing, with no default

我不明白它想要什么。 非常感谢

试试这个:

i<-seq(1,101, by=10)  
x1<- ggplot(d, aes(x=price))
x2<-lapply(i,function(i)
x1+geom_histogram(binwidth=i)

)
To access each plot:
x2[[1]] # for bw 1
x2[[2]] #bw 11 and so on

如果您使用 RStudio:

,您可能还需要考虑包 manipulate
install.packages("manipulate")
library(manipulate)
library(ggplot2)

df <- diamonds

manipulate(
  ggplot(df, aes(x = price)) +
    geom_histogram(binwidth = mybinwidth),
  mybinwidth = slider(10, 100, step = 10, initial = 20)
)

旁白:请注意,如果您使用 ggplot2,则不需要 attach(diamonds)。此外,许多人会反对完全使用 attach - 您现在可能想改掉这个习惯。例如,以下工作正常:

ggplot(diamonds, aes(x = price)) + geom_histogram()