Closed tommmmi closed 2 months ago
Thanks for the report!
We explicitly do not recommend saving ggplot objects to disk. When saving ggplot objects to disk, internal pieces of code needed to generate the plot are saved along with it. When an old plot is loaded, the saved code may be incompatible with the code of the current ggplot version, leading to errors like the one you encountered.
While we do our best to keep the user-facing functions as stable as we reasonably can, no such promises are made about internal code. It would make ggplot2 unmaintainable if internal code has to be backward compatible with previous versions. Therefore, we recommend against saving plot objects to disk. As such, we won't fix rendering old plots with new versions.
There are several things you might try for this issue:
ggsave()
, which is independent of the ggplot2 or grid versions.ggplotGrob(plot)
to disk. This is still subject to changes in {grid} and extensions that declare special makeContent
methods for their graphical objects, but no longer relies on ggplot2's internals.Thank you @teunbrand for the Grob tip!
I quickly tested it out and it seemed to work saving Grob to RDS from v3.4.4 and drawing it in v3.5.0.
R with ggplot2 version 3.4.4:
ggplotGrob(gg_fig) -> gg_grob
saveRDS(gg_grob, file="gg_grob_3_4_4.rds")
R with ggplot2 version 3.5.0:
readRDS("gg_grob_3_4_4.rds") -> gg_grob_old_ver
grid::grid.draw(gg_grob_old_ver)
Works the other way round, too. Save the Grob object from v3.5.0 and grid.draw it in v3.4.4.
Short background: I make quite extensive reports using RMarkdown and they often include figures produced with ggplot2. For faster re-knitting, I like to save finished tables and figures to RDS files and just use readRDS() function in the knit phase.
Few days ago I had to get back to an old project and add a new table to the report but suddenly the file refused to knit and threw an error.
Here is the code to reproduce the bug:
Fresh R session with ggplot2 version 3.4.4:
Fresh R session with ggplot2 version 3.5.0:
This produces 'could not find function "scales_add_defaults"' error:
It took me quite a while to figure out what's causing the error because nothing changed in the report except the newly added table.
I drew the figure with both versions and compared the ggplot-object names:
I think the newer version of ggplot2 cannot render a figure that has been made with version 3.4.4 because version 3.4.4 ggplot-object doesn't have guides- and layout- ggproto-objects in it?