Skip to content

Commit abc70e2

Browse files
authored
stat_count() respects uniqueness of x (#5520)
* instead of removing, `position_stack()` sets incomplete data to missing * adjust test * add test * Add news bullet
1 parent aa41dcb commit abc70e2

File tree

3 files changed

+15
-2
lines changed

3 files changed

+15
-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 (development version)
22

3+
* `stat_count()` treats `x` as unique in the same manner `unique()` does
4+
(#4609).
5+
36
* `position_stack()` no longer silently removes missing data, which is now
47
handled by the geom instead of position (#3532).
58

R/stat-count.R

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,7 @@ StatCount <- ggproto("StatCount", Stat,
7575
x <- data$x
7676
weight <- data$weight %||% rep(1, length(x))
7777

78-
count <- as.numeric(tapply(weight, x, sum, na.rm = TRUE))
79-
count[is.na(count)] <- 0
78+
count <- as.vector(rowsum(weight, x, na.rm = TRUE))
8079

8180
bars <- data_frame0(
8281
count = count,

tests/testthat/test-stat-count.R

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,14 @@ test_that("stat_count() checks the aesthetics", {
44
p <- ggplot(mtcars) + stat_count(aes(factor(gear), mpg))
55
expect_snapshot_error(ggplot_build(p))
66
})
7+
8+
test_that("stat_count() respects uniqueness of `x`", {
9+
# For #4609, converting x to factor loses smallest digits, so here we test
10+
# if they are retained
11+
df <- data_frame0(x = c(1, 2, 1, 2) + rep(c(0, 1.01 * .Machine$double.eps), each = 2))
12+
p <- ggplot(df, aes(x)) + stat_count(position = "identity")
13+
data <- layer_data(p)
14+
15+
expect_length(vec_unique(df$x), 4)
16+
expect_equal(data$y, rep(1, 4))
17+
})

0 commit comments

Comments
 (0)