I've been trying to write a new scale_
function that automatically sets the breaks to the quantiles for that axis (a la Tufte's rangeframe plots). The main thing I'd like to accomplish is accessing the x
and y
variables passed to aes()
from this new scale_
function. I'll outline the issue more below.
I found a StackOverflow thread that delineated how to make the new scale_
function, which is via the following set of functions:
quantile_breaks <- function(value, prob, digits = 1) {
function(x) round(as.numeric(quantile(value, prob)), digits = digits)
}
quantile_trans <- function(val, prob, digits) {
scales::trans_new(
name = "quantile",
transform = function(x) x,
inverse = function(x) x,
breaks = quantile_breaks(val, prob, digits))
}
scale_x_quantile <- function(val, prob = seq(0, 1, 0.25), digits = 1, ...) {
scale_x_continuous(..., trans = quantile_trans(val, prob, digits))
}
This works, but you have to specify val
by directly referring to the dataframe and column, like so:
mtcars %>%
ggplot(aes(x = wt, y = mpg)) +
geom_point() +
scale_x_quantile(val = mtcars$wt)
It's clear that the quantiles of the x axis should (probably) always correspond precisely to the column mapped to x
in aes()
, so I would really like to implement this as a default option. However, it's unclear to me how, or whether it's even possible, to access variables passed to aes()
later on. I knowother layers can access these mappings, but I don't know if it's possible for scale_
functions to access them as well. The ultimate goal is to be able to just run + scale_x_quantile()
without any further arguments, and it sets the breaks to the quantiles for the x
mapping by default.
Is this possible?