Alex
Alex

Reputation: 2780

Save and Load a ggplot plot

I am working on a large shinydashboard and was keeping my code for modeling in a separate file from the main app.R. The problem is that I need to plot my data. This requires that I save my ggplots from one file and load them in my main app.R file. How can I save my ggplots and load them.

As a simple example lets say I have the following

#make plot
> p <- mtcars %>% 
  ggplot(aes(x = mpg, y = cyl))+geom_point()

#save plot
> save(file=here::here("plots/a_plot.Rdata"),p)

#load plot
> p <- load(file=here::here("plots/trans_arima.Rdata"))

> p
[1] "p"

How can I load my ggplot?

Upvotes: 2

Views: 3091

Answers (1)

sammgolo
sammgolo

Reputation: 196

You can save your plot as a png file and then load it back into youyr file you have several option for saving your plot. you could use ggplot2s' ggsave() function or you could use the save_plot() from the cowplot package. save_plot() is said to give you more flexibility when it comes file adjusting hence my pick. You can explore both.

refer to https://rdrr.io/cran/cowplot/man/save_plot.html to read more about save_plot.

tmp = data.frame(first = c('a','b','c','d','e','f','g','h','i','j','k','l','m','n'), 
second = c(2,3,4,5,2,3,4,5,6,3,4,4,6, 7))

plot_tmp = ggplot(tmp, aes(first, second)) + geom_bar(stat = 'identity') 
dev.new()

if("png" %in% installed.packages()){
  library(png)
}else{
  install.packages("png")
  library(png)
}


save_plot("~/plot_tmp.png", plot_tmp, base_height = NULL, base_aspect_ratio = 1.618, 
base_width = 6)

Use the following steps to load files into your shiny using by using the

#read plot

library(OpenImageR)

img<-OpenImageR::readImage("~/plot_tmp.png")
imageShow(img)

Hopefully this helps. To read more about OpenImageR and how you can use it in shiny please go to https://cran.r-project.org/web/packages/OpenImageR/vignettes/The_OpenImageR_package.html

have fun!!!

Upvotes: 3

Related Questions