Skip to content

Commit c9a2d6a

Browse files
authored
Adhere more strictly to bins argument in stat_bin() (#5891)
* try respecting `bins` better * fix #5890 * add test * add news bullet
1 parent 3b83eea commit c9a2d6a

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

NEWS.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,8 @@
8383
`geom_bar()` (#3142).
8484
* Fix a bug in `position_jitterdodge()` where different jitters would be applied
8585
to different position aesthetics of the same axis (@teunbrand, #5818).
86+
* In `stat_bin()`, the default `boundary` is now chosen to better adhere to
87+
the `nbin` argument (@teunbrand, #5882, #5036)
8688

8789
# ggplot2 3.5.1
8890

R/bin.R

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,8 +117,12 @@ bin_breaks_bins <- function(x_range, bins = 30, center = NULL,
117117
} else if (bins == 1) {
118118
width <- diff(x_range)
119119
boundary <- x_range[1]
120+
center <- NULL
120121
} else {
121122
width <- (x_range[2] - x_range[1]) / (bins - 1)
123+
if (is.null(center)) {
124+
boundary <- boundary %||% x_range[1] - width / 2
125+
}
122126
}
123127

124128
bin_breaks_width(x_range, width, boundary = boundary, center = center,

tests/testthat/test-stat-bin.R

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,30 @@ test_that("bins() computes fuzz with non-finite breaks", {
119119
expect_equal(difference[2], 1000 * .Machine$double.eps, tolerance = 0)
120120
})
121121

122+
test_that("bins is strictly adhered to", {
123+
124+
nbins <- c(1, 2, 3, 4, 5, 10, 20, 30, 40, 50)
125+
126+
# Default case
127+
nbreaks <- vapply(nbins, function(bins) {
128+
length(bin_breaks_bins(c(0, 10), bins)$breaks)
129+
}, numeric(1))
130+
expect_equal(nbreaks, nbins + 1)
131+
132+
# Center is provided
133+
nbreaks <- vapply(nbins, function(bins) {
134+
length(bin_breaks_bins(c(0, 10), bins, center = 0)$breaks)
135+
}, numeric(1))
136+
expect_equal(nbreaks, nbins + 1)
137+
138+
# Boundary is provided
139+
nbreaks <- vapply(nbins, function(bins) {
140+
length(bin_breaks_bins(c(0, 10), bins, boundary = 0)$breaks)
141+
}, numeric(1))
142+
expect_equal(nbreaks, nbins + 1)
143+
144+
})
145+
122146
comp_bin <- function(df, ...) {
123147
plot <- ggplot(df, aes(x = x)) + stat_bin(...)
124148
get_layer_data(plot)

0 commit comments

Comments
 (0)