I would like to loop through a long series of qplots
or ggplot2
plots, pausing at each one so I can examine it before moving on.
The following code produces no plots:
library(ggplot2)
par(ask=TRUE)
for(Var in names(mtcars)) {
qplot(mtcars[,Var], wt, data=mtcars, xlab=Var)
}
but if I run this line after running the loop, I DO get a plot:
qplot(mtcars[,Var], wt, data=mtcars, xlab=Var)
What is the reason for this behavior? How do I display the plots within the loop?
Follow up:
Is there a more elegant way to loop through the variables than using mtcars[,Var]
and xlab=Var
?
As the other answers have said, wrap each qplot()
call in print()
(this is R FAQ 7.22). The reason why is that ggplot's aren't printed to the graphics device until print.ggplot
is called on them. print()
is a generic function that dispatches to print.ggplot
behind the scenes.
When you are working in the repl ("read-evaluate-print loop", aka shell) the return value of the previous input line is automatically printed via an implicit call to print()
. That's why
qplot(mtcars[,Var], wt, data=mtcars, xlab=Var)
is working for you. It's nothing to do with scope or the for loop. If you were to put that line anywhere else that isn't directly returning to the repl, such as in a function that returns something else, it would do nothing.
I recently did something similar, and thought I'd mention two extra bits of code that helped. I included this line in the for-loop to make R pause for a moment (in this case, half a second) after printing each plot:
Sys.sleep(0.5)
Alternatively, instead of viewing the plots on the screen, you could save them directly to files and then browse through them at your leisure. Or in my case, I was trying to animate the trajectory of a bee we were tracking, so I imported the image sequence into ImageJ and saved it as an animated gif.
library(ggplot2)
png(file="cars%d.png")
for(Var in names(mtcars)) {
print(qplot(mtcars[,Var], wt, data=mtcars, xlab=Var))
}
dev.off()
Add print
:
library(ggplot2)
par(ask=TRUE)
for(Var in names(mtcars)) {
print(qplot(mtcars[,Var], wt, data=mtcars, xlab=Var))
}
For an explanation see Tavis Rudd's answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With