Skip to content

Commit 2610840

Browse files
authored
stat_bin() accepts functions for argument breaks (#5963)
* `stat_bin()` accepts functions for argument `breaks` * add news bullet
1 parent c95e061 commit 2610840

File tree

4 files changed

+14
-2
lines changed

4 files changed

+14
-2
lines changed

Diff for: NEWS.md

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# ggplot2 (development version)
22

3+
* `stat_bin()` now accepts functions for argument `breaks` (@aijordan, #4561)
34
* (internal) The plot's layout now has a coord parameter that is used to
45
prevent setting up identical panel parameters (#5427)
56
* (internal) rearranged the code of `Facet$draw_panels()` method (@teunbrand).

Diff for: R/stat-bin.R

+4-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
#' outside the range of the data.
2323
#' @param breaks Alternatively, you can supply a numeric vector giving
2424
#' the bin boundaries. Overrides `binwidth`, `bins`, `center`,
25-
#' and `boundary`.
25+
#' and `boundary`. Can also be a function that takes group-wise values as input and returns bin boundaries.
2626
#' @param closed One of `"right"` or `"left"` indicating whether right
2727
#' or left edges of bins are included in the bin.
2828
#' @param pad If `TRUE`, adds empty bins at either end of x. This ensures
@@ -146,6 +146,9 @@ StatBin <- ggproto("StatBin", Stat,
146146
origin = NULL, right = NULL, drop = NULL) {
147147
x <- flipped_names(flipped_aes)$x
148148
if (!is.null(breaks)) {
149+
if (is.function(breaks)) {
150+
breaks <- breaks(data[[x]])
151+
}
149152
if (!scales[[x]]$is_discrete()) {
150153
breaks <- scales[[x]]$transform(breaks)
151154
}

Diff for: man/geom_histogram.Rd

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Diff for: tests/testthat/test-stat-bin.R

+8
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,14 @@ test_that("can use breaks argument", {
6060
expect_equal(out$count, c(1, 2))
6161
})
6262

63+
test_that("breaks computes bin boundaries for function input", {
64+
df <- data.frame(x = c(0, 0, 0, 1:3))
65+
out <- layer_data(ggplot(df, aes(x)) +
66+
geom_histogram(breaks = function(x) c(0, 0.5, 2.5, 7.5)))
67+
68+
expect_equal(out$count, c(3, 2, 1))
69+
})
70+
6371
test_that("fuzzy breaks are used when cutting", {
6472
df <- data_frame(x = c(-1, -0.5, -0.4, 0))
6573
p <- ggplot(df, aes(x)) +

0 commit comments

Comments
 (0)