问题
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')
回答1:
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 <- subset
my.plot <- with(env, {
my.plot <- ggplot(plot.data, ...)
return(my.plot)
})
return(my.plot)
}
来源:https://stackoverflow.com/questions/32192298/small-ggplot-object-1-mb-turns-into-7-gigabyte-rdata-object-when-saved