3

As a follow up to this question, suppose I do something like this:

p <- ggplot(mtcars, aes(mpg)) + geom_histogram(aes(y = ..count..)) + facet_wrap(~am)
r <- print(p)

In the second line I'm calling the print method just so that I can programmatically inspect its return value before adding additional layers to the plot object.

My question: Is there a way to suppress drawing the plot at that point?

Community
  • 1
  • 1
Dave Braze
  • 441
  • 3
  • 14

2 Answers2

5

If you look inside ggplot2:::print.ggplot you'll discover that what you probably want to use is either ggplot_build() or ggplot_gtable(), depending on what information you want to inspect.

ggplot_build returns the data object that is invisibly returned by ggplot2's print method, so that's probably what you're after. ggplot_gtable returns the grobs themselves, which allows for direct modification of the grid graphics objects themselves.

joran
  • 169,992
  • 32
  • 429
  • 468
1

How about:

#Create a temporary plot file
png('TMP_PLOT')

#Inspect return value of plot

#When you're done
dev.off()
#Delete the plot you just generated
unlink('TMP_PLOT')
Omar Wagih
  • 8,504
  • 7
  • 59
  • 75
  • I'm trying to avoid having a plot window pop up at all. If I understand your suggestion, you are saying to send the plot to file rather than to a graphics device, and then delete the file. Is that right? I guess that would serve the purpose, but it seems less elegant than simply not creating the plot to begin with. – Dave Braze Oct 11 '12 at 15:50
  • @DaveBraze This isn't necessary. See my answer. – joran Oct 11 '12 at 15:56