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?

5
  • 2
    Maybe R FAQ 7.22 cran.r-project.org/doc/FAQ/… Commented Mar 30, 2010 at 17:48
  • @rcs Your comment answers the question. Write it as an answer, so as it can be accepted. Commented Mar 30, 2010 at 18:53
  • rcs comment suggest that someone don't read a FAQ ;) Commented Mar 30, 2010 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. Commented Mar 30, 2010 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?". Commented Mar 31, 2010 at 6:08

1 Answer 1

38

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Your advice is correct, but it's not really anything to do with grid - it's just a programming style decision.
+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."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.