循环遍历一系列 qplot
我想循环浏览一系列 qplots
或 ggplot2
图,在每个图处暂停,以便我可以在继续之前检查它。
以下代码不会生成任何绘图:
library(ggplot2)
par(ask=TRUE)
for(Var in names(mtcars)) {
qplot(mtcars[,Var], wt, data=mtcars, xlab=Var)
}
但是如果我在运行循环后运行此行,我确实会得到一个绘图:
qplot(mtcars[,Var], wt, data=mtcars, xlab=Var)
此行为的原因是什么?如何显示循环内的图?
跟进: 有没有比使用 mtcars[,Var] 和 xlab=Var 更优雅的方法来循环变量?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如其他答案所说,将每个
qplot()
调用包装在print()
中(这是 R 常见问题解答 7.22)。原因是在调用print.ggplot
之前,ggplot 不会打印到图形设备。print()
是一个通用函数,在幕后分派到print.ggplot
。当您在 repl(“读取-评估-打印循环”,又名 shell)中工作时,前一个输入行的返回值将通过对
print()
的隐式调用自动打印。这就是为什么qplot(mtcars[,Var], wt, data=mtcars, xlab=Var)
正在为您工作。它与范围或 for 循环无关。如果您将该行放在不直接返回 repl 的任何其他位置,例如返回其他内容的函数中,它将不会执行任何操作。As the other answers have said, wrap each
qplot()
call inprint()
(this is R FAQ 7.22). The reason why is that ggplot's aren't printed to the graphics device untilprint.ggplot
is called on them.print()
is a generic function that dispatches toprint.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 whyqplot(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.我最近做了类似的事情,并且认为我应该提到两段额外的有帮助的代码。我在 for 循环中包含了这一行,以使 R 在打印每个绘图后暂停一会儿(在本例中为半秒):
或者,您可以将它们直接保存到文件中,而不是在屏幕上查看绘图,然后闲暇时浏览它们。或者就我而言,我试图为我们正在跟踪的蜜蜂的轨迹制作动画,因此我将图像序列导入 ImageJ 并将其另存为动画 gif。
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:
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.
添加
print
:有关解释,请参阅 Tavis Rudd 的回答。
Add
print
:For an explanation see Tavis Rudd's answer.