1

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)
}
  • when using ggplot, don't assign aesthetics using the `$` extractor. Just use the variable name, as the scope is already evaluated in the data frame environment. Just ggplot(d, aes(x=price))+ geom_... – Matt74 Jul 07 '15 at 16:37

2 Answers2

1

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))
}
Community
  • 1
  • 1
mts
  • 2,160
  • 2
  • 24
  • 34
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – Limon Monte Jul 08 '15 at 08:31
  • @limonte, could you please specify? in my opinion the code provided above gives the desired output (as far as I understand the question) and is easy enough to compare to the original code to serve as answer. – mts Jul 08 '15 at 08:38
  • @limonte I added some explanation upon your suggestion, thanks for clarifying. However I think the code itself is self-explanatory to who has read the question and answer and taken two minutes to compare the two. Just my opinion. It seems an interesting question to ask on meta as what can be considered a minimal answer. – mts Jul 08 '15 at 12:13
0

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))
erasmortg
  • 3,246
  • 1
  • 17
  • 34