循环播放一系列qplots [英] Loop through a series of qplots
问题描述
我想循环一系列 qplots
或 ggplot2
地块,在每个地块暂停,这样我可以在继续之前检查它。
以下代码不会生成任何图:
par(ask = TRUE)
for(Var in name(mtcars)){
qplot(mtcars [,Var],wt,data = mtcars,xlab = Var)
}
但是如果我在运行循环后运行这一行,得到一个图:
pre $ $ $ $ $ $ $ $ $ $ $
这种行为的原因是什么?如何显示循环内的图?
后续操作:
是否有比使用 mtcars [,Var]
和 xlab = Var
?
正如其他答案所说的那样,在 print()
中包装每个 qplot()
这是 R FAQ 7.22 )。之所以这样,是因为ggplot没有被打印到图形设备上,直到调用 print.ggplot
。 print()
是在后台调度到 print.ggplot
的通用函数。
当您在repl(read-evaluate-print loop,也就是shell)中工作时,前一个输入行的返回值将通过隐式调用自动打印到 print()
。这就是为什么
qplot(mtcars [,Var],wt,data = mtcars,xlab = Var)
正在为您工作。这与范围或for循环无关。如果您要将该行放在其他任何不是直接返回到repl的地方,比如在返回其他东西的函数中,它就什么都不会做。
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.
这篇关于循环播放一系列qplots的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!