Skip to content

Commit ff42a0c

Browse files
committed
combine glyph layers into a single key earlier
1 parent efc53cc commit ff42a0c

File tree

1 file changed

+26
-15
lines changed

1 file changed

+26
-15
lines changed

R/guide-legend.R

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,6 @@ GuideLegend <- ggproto(
271271
c("horizontal", "vertical"), arg_nm = "direction"
272272
)
273273
params$n_breaks <- n_breaks <- nrow(params$key)
274-
params$n_key_layers <- length(params$decor) + 1 # +1 is key background
275274

276275
# Resolve shape
277276
if (!is.null(params$nrow) && !is.null(params$ncol) &&
@@ -387,22 +386,30 @@ GuideLegend <- ggproto(
387386

388387
build_decor = function(decor, grobs, elements, params) {
389388

390-
key_size <- c(elements$width_cm, elements$height_cm) * 10
391-
392-
draw <- function(i) {
393-
bg <- elements$key
394-
keys <- lapply(decor, function(g) {
395-
data <- vec_slice(g$data, i)
396-
if (data$.draw %||% TRUE) {
397-
key <- g$draw_key(data, g$params, key_size)
398-
set_key_size(key, data$linewidth, data$size, key_size / 10)
399-
} else {
400-
zeroGrob()
389+
key_size <- c(elements$width_cm, elements$height_cm)
390+
idx <- seq_len(params$n_breaks)
391+
392+
key_glyphs <- lapply(idx, function(i) {
393+
glyph <- lapply(decor, function(dec) {
394+
data <- vec_slice(dec$data, i)
395+
if (!(data$.draw %||% TRUE)) {
396+
return(zeroGrob())
401397
}
398+
key <- dec$draw_key(data, dec$params, key_size * 10)
399+
set_key_size(key, data$linewidth, data$size, key_size)
402400
})
403-
c(list(bg), keys)
404-
}
405-
unlist(lapply(seq_len(params$n_breaks), draw), FALSE)
401+
402+
width <- vapply(glyph, get_attr, which = "width", default = 0, numeric(1))
403+
width <- max(width, 0, key_size[1], na.rm = TRUE)
404+
height <- vapply(glyph, get_attr, which = "height", default = 0, numeric(1))
405+
height <- max(height, 0, key_size[2], na.rm = TRUE)
406+
407+
grob <- gTree(children = inject(gList(elements$key, !!!glyph)))
408+
attr(grob, "width") <- width
409+
attr(grob, "height") <- height
410+
grob
411+
})
412+
key_glyphs
406413
},
407414

408415
build_labels = function(key, elements, params) {
@@ -791,3 +798,7 @@ deprecated_guide_args <- function(
791798
}
792799
theme
793800
}
801+
802+
get_attr <- function(x, which, exact = TRUE, default = NULL) {
803+
attr(x, which = which, exact = exact) %||% default
804+
}

0 commit comments

Comments
 (0)