我是一名R noob学习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
我不明白它想要什么。 非常感谢
答案 0 :(得分:2)
如果您使用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)
)
除此之外:请注意,如果您使用attach(diamonds)
,则无需ggplot2
。此外,许多人会反对完全使用attach
- 你现在可能想要打破习惯。例如,以下工作正常:
ggplot(diamonds, aes(x = price)) + geom_histogram()
答案 1 :(得分:1)
试试这个:
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