3

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.

Community
  • 1
  • 1
metalaureate
  • 7,572
  • 9
  • 54
  • 93
  • 1
    Dirk's answer should solve your problem, but additionally you should update your version of `ggplot2` (`opts` is deprecated), and it's usually nicer to use `ggsave()` for saving ggplots. – Gregor Thomas Jun 15 '13 at 17:55

1 Answers1

16

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.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • 1
    `ggsave()` only saves-to-file, doesn't display. – smci Mar 31 '14 at 13:07
  • `print(g)` may not render some objects. See http://stackoverflow.com/questions/31458051/store-arrangegrob-to-object-does-not-create-printable-object which suggests `grid.draw()` for them. – Dave X Oct 07 '15 at 18:16
  • But why is that not needed when I type into the console? – pitosalas Jun 05 '17 at 00:40