Skip to content

Commit 13cb186

Browse files
authored
Faster scale_apply (#3759)
1 parent 81ffdd0 commit 13cb186

File tree

3 files changed

+16
-4
lines changed

3 files changed

+16
-4
lines changed

R/layout.R

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -296,10 +296,7 @@ scale_apply <- function(data, vars, method, scale_id, scales) {
296296
abort("`scale_id` must not be `NA`")
297297
}
298298

299-
scale_index <- unname(split(
300-
seq_along(scale_id),
301-
factor(scale_id, levels = seq_along(scales))
302-
))
299+
scale_index <- split_with_index(seq_along(scale_id), scale_id, length(scales))
303300

304301
lapply(vars, function(var) {
305302
pieces <- lapply(seq_along(scales), function(i) {

R/utilities.r

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -640,3 +640,10 @@ flipped_names <- function(flip = FALSE) {
640640
names(ret) <- c(x_aes, y_aes)
641641
ret
642642
}
643+
644+
split_with_index <- function(x, f, n = max(f)) {
645+
if (n == 1) return(list(x))
646+
f <- as.integer(f)
647+
attributes(f) <- list(levels = as.character(seq_len(n)), class = "factor")
648+
unname(split(x, f))
649+
}

vignettes/profiling.Rmd

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,15 @@ To keep track of changes focused on improving the performance of gtable they
5555
are summarised below:
5656

5757
### v`r packageVersion('ggplot2')`
58+
- **Avoid costly factor construction in scale_apply** This issue only really
59+
appeared when plotting huge datasets (>1e6 rows). In order to train and map
60+
the position aesthetics rows has to be matched based on their panel. This
61+
require splitting the row indexes by panel which included a `factor()` call.
62+
The factor constructor is very slow for large vectors and can be simplified
63+
considerably for this specific case. Further, the split can be avoided
64+
completely when there is only one panel
5865

66+
### v3.1.0
5967
- **Caching of calls to `grid::descentDetails()`** The absolute biggest offender
6068
was the construction of titles. In recent versions this has included calls to
6169
`grid::descentDetails()` to ensure that they are aligned across plots, but

0 commit comments

Comments
 (0)