Skip to content

could not find function: Plot saved under old version of ggplot2 cannot be rendered with new version #5865

Closed as not planned
@tommmmi

Description

@tommmmi

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:

library(ggplot2)

## this section is from the ggplot() function examples:
set.seed(1)

sample_df <- data.frame(
  group = factor(rep(letters[1:3], each = 10)),
  value = rnorm(30)
)

group_means_df <- setNames(
  aggregate(value ~ group, sample_df, mean),
  c("group", "group_mean")
)

ggplot(data = sample_df, mapping = aes(x = group, y = value)) +
  geom_point() +
  geom_point(
    mapping = aes(y = group_mean), data = group_means_df,
    colour = 'red', size = 3
  ) -> gg_fig

## save as RDS
saveRDS(gg_fig, file="gg_fig_3_4_4.rds")

Fresh R session with ggplot2 version 3.5.0:

library(ggplot2)

readRDS("gg_fig_3_4_4.rds") -> gg_fig_old_ver

gg_fig_old_ver

This produces 'could not find function "scales_add_defaults"' error:

Error in `geom_point()`:
! Problem while computing aesthetics.Error occurred in the 1st layer.
Caused by error in `scales_add_defaults()`:
! could not find function "scales_add_defaults"
Run `rlang::last_trace()` to see where the error occurred.

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:

> names(gg_fig_3_5_0)
 [1] "data"        "layers"      "scales"      "guides"      "mapping"    
 [6] "theme"       "coordinates" "facet"       "plot_env"    "layout"     
[11] "labels"     
> names(gg_fig_3_4_4)
[1] "data"        "layers"      "scales"      "mapping"     "theme"      
[6] "coordinates" "facet"       "plot_env"    "labels"     

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions