Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# ggplot2 (development version)

* `stat_bin()` now accepts functions for argument `breaks` (@aijordan, #4561)
* (internal) The plot's layout now has a coord parameter that is used to
prevent setting up identical panel parameters (#5427)
* (internal) rearranged the code of `Facet$draw_panels()` method (@teunbrand).
Expand Down
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