tidyverse / ggplot2

An implementation of the Grammar of Graphics in R
https://ggplot2.tidyverse.org
Other
6.39k stars 2k forks source link

`stat_bin()` accepts functions for argument `breaks` #5963

Closed aijordan closed 6 days ago

aijordan commented 1 week ago

This PR is a recreation of #4560 (which can no longer be reopened) and addresses the initial issue discussed in #4561

(Not addressed: rlang lambda function notation for breaks and binwidth)

The changes allow the breaks argument of stat_bin() to take functions as input. Example:

library(ggplot2)

df <- data.frame(
  x = c(rexp(1000), rexp(1000, 5)),
  study = c(rep("A", 1000), rep("B", 1000))
)

ggplot(df, aes(x)) +
  geom_histogram(
    mapping = aes(y = after_stat(density)),
    breaks = \(x) qexp(c(0, .25, .5, .75, .95, .99), 1/mean(x))
  ) +
  facet_wrap(vars(study))

Created on 2024-06-28 with reprex v2.1.0

teunbrand commented 6 days ago

Awesome, thank you for the contribution!