T.G.
T.G.

Reputation: 793

A way to cache a ggplot2 plot

Working with ggplot and shiny, and plotting a lot of data to generate some interactive plots.

I have some performance problems, so I've checked with benchplot() my plotting time, and some of the big plot's are slow. For example, this is the time that it took me to plot one of those plots-

       step user.self sys.self elapsed
1 construct     0.093    0.005   0.101
2     build     1.528    0.044   1.583
3    render     3.292    0.070   3.446
4      draw     3.102    0.189   3.521
5     TOTAL     8.015    0.308   8.651

I can't plot with ggvis or ggbio, because they don't have faceting, which is essential.

Is there a way to cache the constructing, building and rendering of the plot, so I only need to draw it asked, and can save half of the time?

(saving pictures is not a possibility, because the plot are interactive)

Upvotes: 2

Views: 390

Answers (1)

Roland
Roland

Reputation: 132706

Yes, there is:

p <- ggplot(iris, (aes(x = Species, y = Sepal.Length))) +
  geom_boxplot()

g <- ggplotGrob(p)
library(grid)
grid.newpage()
grid.draw(g)


system.time(print(p))
#user  system elapsed 
#0.11    0.00    0.11 


system.time({
  grid.newpage()
  grid.draw(g)
  })
#user  system elapsed 
#0.03    0.00    0.03 

But also consider if you create the right kind of plot. E.g., if you plot hundreds of thousands of points, you are creating a plot that contains huge amounts of overplotting.

Upvotes: 4

Related Questions