Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: suppress drawing of plot when calling print method

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?

like image 431
Dave Braze Avatar asked Oct 18 '25 11:10

Dave Braze


2 Answers

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.

like image 178
joran Avatar answered Oct 20 '25 01:10

joran


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')
like image 42
Omar Wagih Avatar answered Oct 20 '25 02:10

Omar Wagih