Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stat_bin() accepts functions for argument breaks #5963

Merged
merged 2 commits into from
Jun 28, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion R/stat-bin.R
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
#' outside the range of the data.
#' @param breaks Alternatively, you can supply a numeric vector giving
#' the bin boundaries. Overrides `binwidth`, `bins`, `center`,
#' and `boundary`.
#' and `boundary`. Can also be a function that takes group-wise values as input and returns bin boundaries.
#' @param closed One of `"right"` or `"left"` indicating whether right
#' or left edges of bins are included in the bin.
#' @param pad If `TRUE`, adds empty bins at either end of x. This ensures
Expand Down Expand Up @@ -146,6 +146,9 @@ StatBin <- ggproto("StatBin", Stat,
origin = NULL, right = NULL, drop = NULL) {
x <- flipped_names(flipped_aes)$x
if (!is.null(breaks)) {
if (is.function(breaks)) {
breaks <- breaks(data[[x]])
}
if (!scales[[x]]$is_discrete()) {
breaks <- scales[[x]]$transform(breaks)
}
Expand Down
2 changes: 1 addition & 1 deletion man/geom_histogram.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions tests/testthat/test-stat-bin.R
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,14 @@ test_that("can use breaks argument", {
expect_equal(out$count, c(1, 2))
})

test_that("breaks computes bin boundaries for function input", {
df <- data.frame(x = c(0, 0, 0, 1:3))
out <- layer_data(ggplot(df, aes(x)) +
geom_histogram(breaks = function(x) c(0, 0.5, 2.5, 7.5)))

expect_equal(out$count, c(3, 2, 1))
})

test_that("fuzzy breaks are used when cutting", {
df <- data_frame(x = c(-1, -0.5, -0.4, 0))
p <- ggplot(df, aes(x)) +
Expand Down
Loading