Store the result of a plot() call to a variable without sending to current graphics device
ggplot2, pdf, r
Solution
Use `ggplot_build`:
render_plot <- ggplot_build(p + ggtitle("Don't want this plot"))
Problem
This is really one of two questions - either: 1) How do I store the result of a print() call [i.e. `x <- print(something)` ] without sending anything to current graphics output? -or- 2) Is there a function or method in ggplot that will store a plot() call to a variable without calling `plot()` directly? `ggplotGrob` is in the ballpark, but a `ggplotGrob` object doesn't return a list with `$data` in it the same way you get when you store the result of `print()` to a variable. I'm using a technique picked up from this SO answer to pull out the points of a geom_density curve, and then using that data to generate some annotations. I've outlined the issue below -- when I call this as a function, I get the undesired intermediate plot object in my pdf, along with the final plot. The goal is to get rid of that undesired plot; given that base `hist()` has a `plot = FALSE` option I was hopeful that someone who knows something more about R viewports would be able to fix my `plot()` call (solution #1), but any solution is fine, frankly. ``` library(ggplot2) library(plyr) demo <- function (df) { p <- ggplot( df ,aes( x = rating ) ) + geom_density() #plot the object so we can access $data render_plot <- plot(p + ggtitle("Don't want this plot")) #grab just the DF for the density line density_df <- render_plot$data[[1]] #get the maximum density value max_y <- ddply(density_df, "group", summarise, y = max(y)) #join that back to the data to find the matching row anno <- join(density_df, max_y, type = 'inner') #use this to annotate p <- p + annotate( geom = 'text' ,x = anno$x ,y = anno$y ,label = round(anno$density, 3) ) + ggtitle('Keep this plot') return(p) } #call to demo outputs an undesired plot to the graphics device ex <- demo(movies[movies$Comedy ==1,]) plot(ex) #this is problematic if you are trying to make a PDF #a distinct name for the pdf to avoid filesystem issues unq_name <- as.character(format(Sys.time(), "%X")) unq_name <- gsub(':', '', unq_name) pdf(paste(unq_name , '.pdf', sep='')) p <- demo(movies[movies$Drama ==1,]) print(p) dev.off() ```