Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

r - Loop through a series of qplots

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...