In order to change a few layout aspects of a plot made with ggplot I first copied the original ggplot-object into a new variable in order to keep the original intact. When I had updated the copy I noticed that some of the things had also been updated in the original object, as if they were linked. But it didn't happen for all changes, as if it depends on what type of parameter is changed.
Does anyone have an explanation for this behavior and a solution?
Here is an example:
library(tidyverse)
# Create ggplot-object
irisplot <- ggplot(iris, aes(x=Species, y=Sepal.Width, color=Species)) +
geom_boxplot(outlier.alpha=0) +
geom_jitter(width=0.5)
# Copy into new variable
newvariable <- irisplot
tracemem(irisplot)==tracemem(newvariable) # prints FALSE with rlang::duplicate(irisplot) and TRUE without
untracemem(irisplot)
untracemem(newvariable)
##### Linked: layers
# Check original outlier.alpha
irisplot$layers[[1]]$geom_params$outlier.alpha # prints 0 for me
newvariable$layers[[1]]$geom_params$outlier.alpha # prints 0 for me
# Update outlier.alpha in copy
newvariable$layers[[1]]$geom_params$outlier.alpha <- 1
tracemem(irisplot)==tracemem(newvariable)
# Check updated outlier.alpha
newvariable$layers[[1]]$geom_params$outlier.alpha # prints 1 for me
irisplot$layers[[1]]$geom_params$outlier.alpha # prints 1 for me
untracemem(irisplot)
untracemem(newvariable)
##### Not linked: labels
# Check original x-label
irisplot$labels$x # prints "Species" for me
newvariable$labels$x # prints "Species" for me
# Updated x-label
newvariable$labels$x <- "New label"
# Check updated x-label
newvariable$labels$x # prints "New label" for me
irisplot$labels$x # prints "Species" for me
I included tracemem
to check if it's due to sharing memory address initially, but replacing the copying line with newvariable <- rlang::duplicate(irisplot)
doesn't change the linked behavior.
A slightly related question: It seems to do the trick to modify an existing ggplot-object this way, by overwriting specific parameters, but is there a cleaner/official way of going about it? For eg. labels I can use theme, but how about for geom-specific things?
Edit:
My setup: Windows 10, R version 3.6.1, ggplot2 3.3.2, rlang 0.4.7
A colleague who gets the same result: windows 10, R version 4.0.3, ggplot2 3.3.2, rlang 0.4.7