1

Is there a way to read a saved plot in to R, and assign it an object - the equivalent of reading in a csv?

df<-read.csv('test.data.csv')

The end goal is that I have 500 plots that were saved using ggsave() that I'd like to reposition via cowplot(), which only seems to be able to access objects in the active working environment.

Thanks for any insight.

jxw
  • 23
  • 1
  • 8
  • 1
    How was the plot saved? – Dason Mar 30 '17 at 17:14
  • A function iteratively exported each plot as a .png using ggsave(), so the back end data is lost from the working environment as the plots are exported. – jxw Mar 30 '17 at 17:42

2 Answers2

1

No, once the plot is saved as a .jpeg or .pdf or whatever image format you use, the back end data that is stored in the R object is lost.

You can save the R plot object using the save() function and then call that back with the load() function. However this will not be saved in a format that most other programs will recognize as an image. It is not something you could load into powerpoint.

If all you need is loading a straight up image into R, then see the answers to this question: how to read.jpeg in R 2.15

Community
  • 1
  • 1
Bishops_Guest
  • 1,422
  • 13
  • 13
  • Got it. So perhaps I have two options - 1) create all the plots again, save them as temp objects, and then use cowplot() to plot side by side; 2) load() the objects, format, and export again (if I'm understanding save() and load() correctly?) I don't need R in this case to have the back end data on store, just the static image file is in theory fine. – jxw Mar 30 '17 at 17:38
  • By the sound of it, in 2) you would need to create and save the objects again anyway. If you only need the static image, then the `jpeg` or `rgdal` (depending on the format) package may do what you need. – Bishops_Guest Mar 30 '17 at 18:04
  • If you want to use any of the plot alignment functions of `cowplot` you are going to need some of that back end plot layer data. If you already have a function that generates the plots you are interested in then you can make a list of plots using `lapply`. – Bishops_Guest Mar 30 '17 at 18:10
0

You can save individual plot objects to your hard drive in an RDS file (1 object per RDS file):

# sample plot
plot = ggplot(data = cars, aes(x = speed, y = dist)) + geom_point()

# save plot object
saveRDS(plot, file = "C:/data/plot.RDS")

# read plot object back into r 
plot <- readRDS("C:/data/plot.RDS")
plot
Dan Tarr
  • 209
  • 3
  • 8