36

I'd like to spawn several graphics windows from within a function in R using ggplot graphics...

testf <- function(a, b) {
  devAskNewPage(TRUE)
  qplot(a, b);
  # grid.newpage(recording = TRUE)
  dev.new()
  qplot(a, a+a);
  # grid.newpage(recording = TRUE)
  dev.new()
  qplot(b, b+b);
}

library(ggplot2)

x <- rnorm(50)
y <- rnorm(50)
testf(x, y)

However, neither dev.new() nor grid.newpage() seems to flush the preceding plot.

I know that, in R, functions normally only produce the last thing they evaluate, but I'd like to understand the process better and to learn of any possible workarounds.

Thoughts?

Ari B. Friedman
  • 71,271
  • 35
  • 175
  • 235
William Doane
  • 1,416
  • 12
  • 20
  • 2
    Maybe R FAQ 7.22 http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-do-lattice_002ftrellis-graphics-not-work_003f – rcs Mar 30 '10 at 17:48
  • @rcs Your comment answers the question. Write it as an answer, so as it can be accepted. – gd047 Mar 30 '10 at 18:53
  • rcs comment suggest that someone don't read a FAQ ;) – Marek Mar 30 '10 at 20:19
  • 2
    I'm not sure I SHOULD have been able to spot this one... "7.22 Why do lattice/trellis graphics not work?" hardly speaks to my questions about ggplot and output. FAQs only work when they're well indexed and mention all the likely key phrases someone is likely to search. – William Doane Mar 30 '10 at 21:03
  • I agree with you. In your case there is no straight connection between your problem and FAQ7.22. On the other hand your problem isn't "flush the preceding plot", cause if you e.g. write to `png` then both plot will be empty. Then you may ask question "why my ggplot2 not work?". – Marek Mar 31 '10 at 06:08

1 Answers1

37

The grid-based graphics functions in lattice and ggplot2 create a graph object, but do not display it. The print() method for the graph object produces the actual display, i.e.,

print(qplot(x, y))

solves the problem.

See R FAQ 7.22.

rcs
  • 67,191
  • 22
  • 172
  • 153
  • 2
    Your advice is correct, but it's not really anything to do with grid - it's just a programming style decision. – hadley Mar 30 '10 at 19:16
  • 12
    +1: This had me stumped for 30 minutes. This gotcha is so important it is worth reproducing: ***"A print() method for the graph object is required to produce an actual display. When you use (ggplot2, grid, etc.) 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."*** – smci May 12 '12 at 21:45