循环的Binwidth

时间:2015-07-07 14:05:19

标签: r ggplot2

这有效

for (i in 1:50) {
    plot(1,i)
}

这不起作用,为什么?它是 binwidth 我想要改变

d <- diamonds
for (i in 1:50 by=10) {
ggplot(aes(x = d$price), data = d) + geom_histogram(color = 'black', fill = '#099DD1', binwidth = i)
}

2 个答案:

答案 0 :(得分:1)

在循环中绘图(或通过source)有一些意想不到的陷阱(Plotting during a loop in RStudioR: ggplot does not work if it is inside a for loop although it works outside of it)所以这里有助于将其括在print()中。另请注意,您应使用seq(from, to, by),如下所示:

d <- diamonds
for (i in seq(1,50,10)) {
  print(ggplot(aes(x = d$price), data = d) + geom_histogram(color = 'black', fill = '#099DD1', binwidth = i))
}

答案 1 :(得分:0)

它必须是一个循环吗?你可以试试这个:

 lapply(seq(1,50,10), function(x) ggplot(aes(x = d$price), data = d) + geom_histogram(color = 'black', fill = '#099DD1', binwidth = x))