Skip to content

Instantly share code, notes, and snippets.

@paleolimbot
Created June 6, 2019 23:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paleolimbot/c384731743f5492807751f274a3973cb to your computer and use it in GitHub Desktop.
Save paleolimbot/c384731743f5492807751f274a3973cb to your computer and use it in GitHub Desktop.
A ggplot2 scale that can handle a data frame column
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