Created
June 6, 2019 23:30
-
-
Save paleolimbot/c384731743f5492807751f274a3973cb to your computer and use it in GitHub Desktop.
A ggplot2 scale that can handle a data frame column
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(ggplot2) | |
ScaleDataFrame <- ggproto( | |
"ScaleDataFrame", Scale, | |
aesthetics = NULL, | |
plot_env = emptyenv(), | |
scales_list = ggproto(NULL, ggplot2:::ScalesList), | |
transform = function(self, x) { | |
x[] <- purrr::map2( | |
names(x), x, | |
function(col_name, col) self$get_scale(x, col_name)$transform(col) | |
) | |
x | |
}, | |
train = function(self, x, ...) { | |
purrr::walk2( | |
names(x), x, | |
function(col_name, col) self$get_scale(x, col_name)$train(col, ...) | |
) | |
}, | |
map = function(self, x, ...) { | |
x[] <- purrr::map2( | |
names(x), x, | |
function(col_name, col) self$get_scale(x, col_name)$map(col, ...) | |
) | |
x | |
}, | |
get_scale = function(self, df, col) { | |
fake_aesthetics <- paste0(self$aesthetics, ":::", col) | |
if (is.null(self$scales_list$get_scales(fake_aesthetics[1]))) { | |
scale <- ggplot2:::find_scale(self$aesthetics[1], df[[col]], self$plot_env) | |
scale$aesthetics <- fake_aesthetics | |
self$scales_list$add(scale) | |
} | |
self$scales_list$get_scales(fake_aesthetics[1]) | |
}, | |
clone = function(self) { | |
ggproto(NULL, self, scales_list = self$scales_list$clone()) | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment