在函数R中时,ggplot2看起来不起作用 [英] ggplot2 does not appear to work when inside a function R

查看:346
本文介绍了在函数R中时,ggplot2看起来不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对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看起来不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆