Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

r - small ggplot object (1 mb) turns into 7 gigabyte .Rdata object when saved

I have a series of ggplot objects that I'm trying to save to an .rdata file to load into a Markdown document later. The ggplot object itself is quite small (a few KB). But, when I try to save the object as an .rdata file for later retrieval, the resulting .rdata file is now over 8 gigabytes. I've tried saving the plot directly from the GUI, saving as an .rds... Saving as a .pdf or other image results in a normal image of a few KB.

I'm stumped, has anyone else encountered this problem?

Sample workflow below, I can't provide reproducible code for the problem since I can't upload the dataframe required to make this plot

mcmsy<- (ggplot(data = subset(MonteCarlo, Policy == 'RBFM' & 
Year == BaselineYear), aes(MSY), alpha = 0.8) + geom_density(fill = 'steelblue2'))

object.size(mcmsy)

save(mcmsy, file = 'mcmsy_plot.rdata')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I stumbled upon this problem as well. This is indeed related to the environment. If you want to save your plots as an Rdata file, then you should be creating a new environment inside the function that is generating your plot, so that the complete environment doesn't get saved. Example:

makePlot <- function(plot.data){
  env <- new.env(parent = globalenv())
  env$subset <- plot.data

  my.plot <- with(env, {
    my.plot <- ggplot(subset, ...) 
    return(my.plot)
  })

  return(my.plot)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...