Skip to content

Commit 271a3e2

Browse files
committed
Fix off-by-one error in stat_bar.
Fixes #1487
1 parent a4ba0bd commit 271a3e2

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

NEWS.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
# ggplot2 2.0.0.9000
22

3+
* `geom_histgram(bins = n)` now gives a histogram with `n` bins, not `n + 1`
4+
(#1487).
5+
36
* `geom_tile()` once again accepts `width` and `height` parameters (#1513).
47

58
* Add access to `bw` argument of `density` in `stat_density`, which makes

R/stat-bin.r

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,14 @@ bin <- function(x, weight=NULL, binwidth=NULL, bins=NULL, origin=NULL, breaks=NU
9494
weight[is.na(weight)] <- 0
9595

9696
if (is.null(range)) range <- range(x, na.rm = TRUE, finite = TRUE)
97-
if (is.null(bins)) bins <- 30
98-
if (is.null(binwidth)) binwidth <- diff(range) / bins
97+
98+
if (is.null(bins)) {
99+
bins <- 30
100+
} else {
101+
stopifnot(is.numeric(bins), length(bins) == 1, bins > 1)
102+
}
103+
104+
if (is.null(binwidth)) binwidth <- diff(range) / (bins - 1)
99105

100106
if (is.integer(x)) {
101107
bins <- x

tests/testthat/test-stat-bin.R

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,16 @@ test_that("stat_bin throws error when y aesthetic present", {
1010
"Unknown parameters: y")
1111
})
1212

13+
test_that("bins specifies the number of bins", {
14+
df <- data.frame(x = 1:100)
15+
out <- function(x, ...) {
16+
layer_data(ggplot(df, aes(x)) + geom_histogram(..., drop = TRUE))
17+
}
18+
19+
expect_equal(nrow(out(bins = 2)), 2)
20+
expect_equal(nrow(out(bins = 10)), 10)
21+
})
22+
1323
test_that("stat_count throws error when y aesthetic present", {
1424
dat <- data.frame(x = c("a", "b", "c"), y = c(1, 5, 10))
1525

0 commit comments

Comments
 (0)