Skip to content

Commit 0287675

Browse files
committed
get_layer_data(), get_layer_grob() accept layer names
1 parent a27af21 commit 0287675

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

R/plot-build.R

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
#' plot). In `get_panel_scales()`, the row of a facet to return scales for.
1717
#' @param j An integer. In `get_panel_scales()`, the column of a facet to return
1818
#' scales for.
19+
#' @param name A scalar string. In `get_layer_data()` and `get_layer_grob()`, the name of the layer
20+
#' to return. If provided and existing, this takes precedence over `i`.
1921
#' @param ... Not currently in use.
2022
#' @seealso
2123
#' [print.ggplot()] and [benchplot()] for
@@ -141,9 +143,16 @@ build_ggplot <- S7::method(ggplot_build, class_ggplot) <- function(plot, ...) {
141143

142144
#' @export
143145
#' @rdname ggplot_build
144-
get_layer_data <- function(plot = get_last_plot(), i = 1L) {
145-
ggplot_build(plot)@data[[i]]
146+
get_layer_data <- function(plot = get_last_plot(), i = 1L, name = NA) {
147+
if (is.na(name)) {
148+
idx <- i
149+
} else {
150+
name <- arg_match0(name, names(p@layers))
151+
idx <- which(name == names(p@layers))
152+
}
153+
ggplot_build(plot)@data[[idx]]
146154
}
155+
147156
#' @export
148157
#' @rdname ggplot_build
149158
layer_data <- get_layer_data
@@ -168,10 +177,15 @@ layer_scales <- get_panel_scales
168177

169178
#' @export
170179
#' @rdname ggplot_build
171-
get_layer_grob <- function(plot = get_last_plot(), i = 1L) {
180+
get_layer_grob <- function(plot = get_last_plot(), i = 1L, name = NA) {
172181
b <- ggplot_build(plot)
173-
174-
b@plot@layers[[i]]$draw_geom(b@data[[i]], b@layout)
182+
if (is.na(name)) {
183+
idx <- i
184+
} else {
185+
idx <- arg_match0(name, names(p@layers))
186+
idx <- which(name == names(p@layers))
187+
}
188+
b@plot@layers[[idx]]$draw_geom(b@data[[idx]], b@layout)
175189
}
176190

177191
#' @export

0 commit comments

Comments
 (0)