Reputation: 51
This works
for (i in 1:50) {
plot(1,i)
}
This does not work, why? it is binwidth I want to have changing
d <- diamonds
for (i in 1:50 by=10) {
ggplot(aes(x = d$price), data = d) + geom_histogram(color = 'black', fill = '#099DD1', binwidth = i)
}
Upvotes: 1
Views: 143
Reputation: 2190
plotting in a loop (or through source
) has some unexpected pitfalls (Plotting during a loop in RStudio, R: ggplot does not work if it is inside a for loop although it works outside of it) so here it helps to enclose it in a print()
. Also notice that you should use seq(from, to, by)
as below:
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))
}
Upvotes: 1
Reputation: 3278
Does it have to be a loop? You could try this instead:
lapply(seq(1,50,10), function(x) ggplot(aes(x = d$price), data = d) + geom_histogram(color = 'black', fill = '#099DD1', binwidth = x))
Upvotes: 0