R 如何动态设置直方图宽度

R 如何动态设置直方图宽度,r,ggplot2,R,Ggplot2,我是一个彻头彻尾的学习者。 我不明白为什么第一个片段有效,而第二个片段无效。我想在没有猜测的情况下找到一个好的箱子宽度,所以我尝试了一个不起作用的实验 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 sub

我是一个彻头彻尾的学习者。 我不明白为什么第一个片段有效,而第二个片段无效。我想在没有猜测的情况下找到一个好的箱子宽度,所以我尝试了一个不起作用的实验

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
我不明白它想要什么。 非常感谢

试试这个:

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

<代码> i 如果您使用的是:

,您可能还需要考虑包<代码>操作< /代码>。


你需要使用
lappy
。哇!非常感谢@Jason,你的解决方案让我大开眼界!还感谢您提供有关附加的提示…我只是不知道还有什么更好的。@user4056279很高兴我能提供帮助。学习R是一场马拉松,而不是一场冲刺。对于其他闯入R涅磐的noobs来说,我在搜索“为什么不连接”后发现了这一点。它列出了几个更安全的替代方案。感谢您的解决方案@Metrics,我发现它很有用,也很有启发性。
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
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)
)
ggplot(diamonds, aes(x = price)) + geom_histogram()