Skip to content

Commit a03d41b

Browse files
committed
add 'meta' property to track arbitrary fields
1 parent a7dab26 commit a03d41b

File tree

2 files changed

+31
-10
lines changed

2 files changed

+31
-10
lines changed

R/all-classes.R

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -133,22 +133,29 @@ class_ggplot <- S7::new_class(
133133
facet = class_facet,
134134
layout = class_layout,
135135
labels = class_labels,
136+
meta = S7::class_list,
136137
plot_env = S7::class_environment
137138
),
138139
constructor = function(data = waiver(), layers = list(), scales = NULL,
139140
guides = NULL, mapping = aes(), theme = NULL,
140141
coordinates = coord_cartesian(default = TRUE),
141142
facet = facet_null(), layout = NULL,
142-
labels = labs(), plot_env = parent.frame()) {
143+
labels = labs(), meta = list(),
144+
plot_env = parent.frame()) {
143145
S7::new_object(
144146
S7::S7_object(),
145-
data = data, layers = layers,
146-
scales = scales %||% scales_list(),
147-
guides = guides %||% guides_list(),
148-
mapping = mapping, theme = theme %||% theme(),
149-
coordinates = coordinates, facet = facet,
150-
layout = layout %||% ggproto(NULL, Layout),
151-
labels = labels, plot_env = plot_env
147+
data = data,
148+
layers = layers,
149+
scales = scales %||% scales_list(),
150+
guides = guides %||% guides_list(),
151+
mapping = mapping,
152+
theme = theme %||% theme(),
153+
coordinates = coordinates,
154+
facet = facet,
155+
layout = layout %||% ggproto(NULL, Layout),
156+
labels = labels,
157+
meta = meta,
158+
plot_env = plot_env
152159
)
153160
}
154161
)

R/plot.R

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -237,12 +237,26 @@ S7::method(plot, class_ggplot) <- `print.ggplot2::ggplot`
237237

238238
#' @export
239239
`$.ggplot2::gg` <- function(x, i) {
240-
`[[`(S7::props(x), i)
240+
if (!S7::prop_exists(x, i) && S7::prop_exists(x, "meta")) {
241+
# This is a trick to bridge a gap between S3 and S7. We're allowing
242+
# for arbitrary fields by reading/writing to the 'meta' field when the
243+
# index does not point to an actual property.
244+
# The proper way to go about this is to implement new fields as properties
245+
# of a ggplot subclass.
246+
S7::prop(x, "meta")[[i]]
247+
} else {
248+
`[[`(S7::props(x), i)
249+
}
241250
}
242251

243252
#' @export
244253
`$<-.ggplot2::gg` <- function(x, i, value) {
245-
S7::props(x) <- `[[<-`(S7::props(x), i, value)
254+
if (!S7::prop_exists(x, i) && S7::prop_exists(x, "meta")) {
255+
# See explanation in `$.ggplot2::gg`
256+
S7::prop(x, "meta")[[i]] <- value
257+
} else {
258+
S7::props(x) <- `[[<-`(S7::props(x), i, value)
259+
}
246260
x
247261
}
248262

0 commit comments

Comments
 (0)