让foreach()和ggplot2相处 [英] Getting foreach() and ggplot2 to get along
问题描述
pre $国家< - isplit(无人驾驶飞机,无人驾驶飞机$ v3)
foreach(country = countries)%dabar {file = paste(output.exp,/工作满意度直方图in,country $ key [[1]],.png, (国家)#ggplot2不赞赏列表nextElem()产生
ggplot(country.df,aes(x = value)。 v51))+ geom_histogram()
dev.off()
}
真正离奇的事情?我可以运行isplit(),设置 country< - nextElem(countries)
,然后运行代码而不发送foreach行 - 并得到一个可爱的情节。如果我发送foreach,我得到一些空白的.png文件。
在此先感谢您的帮助。
我完全可以用标准的R循环做这个,但是我真的想更好地掌握 foreach
。
如果您想显示,您需要 print
print(ggplot(country.df,aes(x = value.v51))+ geom_histogram())
默认情况下,ggplot命令返回一个绘图对象,但是命令本身并不实际显示绘图;这是通过 print
命令完成的。请注意,当您以交互方式运行代码时,将会打印命令的结果,这就是为什么您经常不需要显式打印的原因。但是,当包装在 foreach
中时,您需要明确地打印,因为正文中的命令结果不会被回显。
I have a set of survey data, and I'd like to generate plots of a particular variable, grouped by the respondent's country. The code I have written to generate the plots so far is:
countries <- isplit(drones, drones$v3)
foreach(country = countries) %dopar% {
png(file = paste(output.exp, "/Histogram of Job Satisfaction in ", country$key[[1]], ".png", sep = ""))
country.df <- data.frame(country) #ggplot2 doesn't appreciate the lists nextElem() produces
ggplot(country.df, aes(x = value.v51)) + geom_histogram()
dev.off()
}
The truly bizarre thing? I can run the isplit(), set country <- nextElem(countries)
, and then run through the code without sending the foreach line - and get a lovely plot. If I send the foreach, I get some blank .png files.
Thanks in advance for your help.
I can definitely do this with standard R loops, but I'd really like to get a better grasp on foreach
.
You need to print
the plot if you want it to display:
print(ggplot(country.df, aes(x = value.v51)) + geom_histogram())
By default, ggplot commands return a plot object but the command itself does not actually display the plot; that is done with the print
command. Note that when you run code interactively, results of commands get printed which is why you often don't need the explicit print. But when wrapping in a foreach
, you need to explicitly print since the results of the commands in the body will not be echoed.
这篇关于让foreach()和ggplot2相处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!