When I modify parts of a duplicated Geom object, this also modifies the underlying original Geom. Why?
(Big big thanks to user Stefan to identify this problem via comment on a now deleted previous question of mine).
library(ggplot2)
GeomFunction$required_aes
#> [1] "x" "y"
GeomFunction2 <- GeomFunction
GeomFunction2$required_aes <- c("x", "y", "fun")
GeomFunction$required_aes
#> [1] "x" "y" "fun"
Created on 2022-01-09 by the reprex package (v2.0.1)
Because ggproto class objects are environments instead of list-like structures, as can be checked with is.environment(GeomFunction)
. Environments do not follow the copy-on-modify heuristics that e.g. a vector adheres to.
The correct way to make a copy for modification purposes is with the ggproto
constructor. Technically, you're making a child instance of GeomFunction
.
library(ggplot2)
GeomFunction2 <- ggproto(NULL, GeomFunction)
GeomFunction2$required_aes <- c("x", "y", "fun")
identical(GeomFunction$required_aes, GeomFunction2$required_aes)
#> [1] FALSE
Created on 2022-01-09 by the reprex package (v2.0.1)
In addition, because ggproto objects are environments, we can use ls()
to see what they contain.
ls(GeomFunction2)
#> [1] "required_aes" "super"
ls(GeomFunction)
#> [1] "draw_panel" "super"
ls(Geom)
#> [1] "aesthetics" "default_aes" "draw_group" "draw_key"
#> [5] "draw_layer" "draw_panel" "extra_params" "handle_na"
#> [9] "non_missing_aes" "optional_aes" "parameters" "required_aes"
#> [13] "setup_data" "setup_params" "use_defaults"
You can see that every layer in the hierarchy only contains the changes relative to the parent, and a mysterious super
object, which is a function. When the super
function is called, you can see that it retrieves the parent class.
class(GeomFunction2$super())
#> [1] "GeomFunction" "GeomPath" "Geom" "ggproto" "gg"
Created on 2022-01-09 by the reprex package (v2.0.1)
The absence of a super
object in Geom
suggests that Geom
is the root class.
The reason that the ggproto
class exists is to allow extensions to reuse large chunks of code, without having to build them from scratch. In theory, ggproto is similar to R6 or reference class object-oriented programming, but I think R6/reference classes had some drawbacks that wouldn't allow cross-package inheritance of their classes.