2

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?

3
  • That's not how load works; load stores objects in the current environment; p (the return object of load) is a character vector of the names of the objects (see ?load). So load("plots/trans_arima.Rdata"); p; will plot object p that is stored in "plots/trans_arima.Rdata" (provided there is one). Commented Jun 19, 2018 at 22:51
  • @MauritsEvers how would you suggest I load my plot in a new file? Commented Jun 19, 2018 at 22:52
  • 2
    You could do load("plots/trans_arima.Rdata"); new_name <- p; Commented Jun 19, 2018 at 22:54

1 Answer 1

3

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!!!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.