我对R有点新 - 我一直在试图将R脚本封装为一个函数,所以我可以从Rserve中调用它。有人知道为什么ggplot2不能在一个函数内部工作,但在其外部工作正常吗?
png('polarity.png' ) ggplot(sent_df,aes(x = polarity))+ geom_bar(aes(y = .. count ..,fill = polarity))+ scale_fill_brewer(palette =RdGy )+ 实验室(x =极性类别,y =会话数量)+ opts(title =Facebook上的帖子的情感分析\\\(按极性分类), plot.title = theme_text(size = 12)) dev.off()<这可能与它有关 ggplot2产生错误时在功能或S4中使用,但我没有收到我可以检测到的错误 - 我只是没有输出。
解决方案这是一个R FAQ - 你需要在它周围的 print(),或者是 ggsave()特别是ggplot2。
常见问题解答:
7.22为什么格子/格子图形不起作用? 最可能的原因是你忘记告诉R显示图。像 xyplot()这样的格子函数创建一个图形对象,但是不显示它(ggplot2图形也是如此,而Trellis 图形在S-Plus中)。图形对象的 print()方法产生的实际显示。当您在命令行中交互使用这些函数时,结果会自动打印,但是在您自己的函数中会自动打印,但是在 source()或中,您将需要一个明确的 print()语句。
I'm a bit new to R - I've been trying to wrap an R script as a function so I can call it from Rserve. Does anyone know why ggplot2 would not work inside a function yet works just fine outside of it?
png('polarity.png') ggplot(sent_df, aes(x=polarity)) + geom_bar(aes(y=..count.., fill=polarity)) + scale_fill_brewer(palette="RdGy") + labs(x="polarity categories", y="number of conversatins") + opts(title = "Sentiment Analysis of Posts on Facebook\n(classification by polarity)", plot.title = theme_text(size=12)) dev.off()This may have something to do with it ggplot2 produces error when used in function or S4 but I'm not getting an error that I can detect - I just get no output.
解决方案It's an R FAQ -- you need print() around it, or a ggsave() which is particular to ggplot2.
From the FAQ:
7.22 Why do lattice/trellis graphics not work?
The most likely reason is that you forgot to tell R to display the graph. Lattice functions such as xyplot() create a graph object, but do not display it (the same is true of ggplot2 graphics, and Trellis graphics in S-Plus). The print() method for the graph object produces the actual display. When you use these functions interactively at the command line, the result is automatically printed, but in source() or inside your own functions you will need an explicit print() statement.
更多推荐
在函数R中时,ggplot2看起来不起作用
发布评论