Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't plot ggplot2 objects created with R 3.x into R 4.x imported from a RDS file

Tags:

r

ggplot2

r-4.0.0

I exported a list with some ggplot2 objects into a .RDS file, generated from a R 3.6.1 session. Then, tried importing it into a R 4.0.0 session and got the following error:

Error in identicalUnits(x) : 
  old version of unit class is no longer allowed

I can read and import these plots into an R object, but CAN'T plot. They actually have all the data within (data, layers, scales mapping...) but ggplot2 is not plotting them.

Is there any way around it? Have any of you encountered with this issue? Would ggplot2have plans to update the library so we can import older version plots? Hope you can help me find a solution, or at least a patch. Thanks!

like image 609
Bernardo Avatar asked May 28 '20 14:05

Bernardo


3 Answers

Saving ggplot2 objects into .Rds files is generally discouraged, because there is absolutely no guarantee that they will still work if either ggplot2 or (in this case) R is upgraded to the next release, even if it is minor release. ggplot2 objects contain large amounts of executable code (closures) as well as internal data structures, and these generally get out of sync whenever we generate a plot with one ggplot2 version and then try to print with another.

Another problem with saving a ggplot2 object to .Rds is that the entire R environment is saved as well, so that your .Rds file may blow up if you happen to have a large amount of data loaded into your session.

The only two safe approaches to retaining plots across versions are to 1. save your raw data and code that generates the plot or 2. save the plot output as .png, .pdf, etc.

like image 56
Claus Wilke Avatar answered Oct 18 '22 01:10

Claus Wilke


I also ran into this issue, and was able to solve it by changing the theme of the loaded plot.

g <- readRDS(my_plots_file_path)
g$theme <- ggplot2::theme_minimal()

I think this is because that is where all the instances of unit variables existed in my plot.

like image 22
Michael Misson Avatar answered Oct 18 '22 00:10

Michael Misson


I had the same issue which happened after I had globally set a custom theme. I noticed that if I re-defined the theme with 'complete = F' and then set the new theme the plotting works normally. Don't have a better solution yet unfortunately. This also happened with ggplot objects that were newly coded, i.e. not read from a .Rds file.

like image 38
Noa Eren Avatar answered Oct 18 '22 00:10

Noa Eren