Skip to content

Commit 256b26a

Browse files
Allow stat_bin() to compute over single-unique-value data (#3047)
* Use the fixed binwidth when the range is 0-width
1 parent 26cd107 commit 256b26a

File tree

3 files changed

+14
-0
lines changed

3 files changed

+14
-0
lines changed

NEWS.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@
4747
* `stat_bin()` will now error when the number of bins exceeds 1e6 to avoid
4848
accidentally freezing the user session (@thomasp85).
4949

50+
* `stat_bin()` now handles data with only one unique value (@yutannihilation #3047).
51+
5052
# ggplot2 3.1.0
5153

5254
## Breaking changes

R/bin.R

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,9 @@ bin_breaks_bins <- function(x_range, bins = 30, center = NULL,
101101
bins <- as.integer(bins)
102102
if (bins < 1) {
103103
stop("Need at least one bin.", call. = FALSE)
104+
} else if (zero_range(x_range)) {
105+
# 0.1 is the same width as the expansion `expand_default()` gives for 0-width data
106+
width <- 0.1
104107
} else if (bins == 1) {
105108
width <- diff(x_range)
106109
boundary <- x_range[1]

tests/testthat/test-stat-bin.R

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,15 @@ test_that("breaks are transformed by the scale", {
6969
expect_equal(out2$xmin, sqrt(c(1, 2.5)))
7070
})
7171

72+
test_that("geom_histogram() can be drawn over a 0-width range (#3043)", {
73+
df <- data_frame(x = rep(1, 100))
74+
out <- layer_data(ggplot(df, aes(x)) + geom_histogram())
75+
76+
expect_equal(nrow(out), 1)
77+
expect_equal(out$xmin, 0.95)
78+
expect_equal(out$xmax, 1.05)
79+
})
80+
7281
# Underlying binning algorithm --------------------------------------------
7382

7483
comp_bin <- function(df, ...) {

0 commit comments

Comments
 (0)