Skip to content

Commit b1874b2

Browse files
authored
Default bar width calculated panel-wise (#5125)
* `geom_bar()` uses panelwise resolution * Add test * Add NEWS bullet
1 parent 64814b0 commit b1874b2

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

NEWS.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# ggplot2 (development version)
22

3+
* The default width of `geom_bar()` is now based on panel-wise resolution of
4+
the data, rather than global resolution (@teunbrand, #4336).
35
* To apply dodging more consistently in violin plots, `stat_ydensity()` now
46
has a `drop` argument to keep or discard groups with 1 observation.
57
* Aesthetics listed in `geom_*()` and `stat_*()` layers now point to relevant

R/geom-bar.R

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,10 @@ GeomBar <- ggproto("GeomBar", GeomRect,
144144
data$flipped_aes <- params$flipped_aes
145145
data <- flip_data(data, params$flipped_aes)
146146
data$width <- data$width %||%
147-
params$width %||% (resolution(data$x, FALSE) * 0.9)
147+
params$width %||% (min(vapply(
148+
split(data$x, data$PANEL),
149+
resolution, numeric(1), zero = FALSE
150+
)) * 0.9)
148151
data$just <- params$just %||% 0.5
149152
data <- transform(data,
150153
ymin = pmin(y, 0), ymax = pmax(y, 0),

tests/testthat/test-geom-bar.R

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,27 @@ test_that("geom_bar works in both directions", {
2424
y$flipped_aes <- NULL
2525
expect_identical(x, flip_data(y, TRUE))
2626
})
27+
28+
test_that("geom_bar default widths considers panels", {
29+
30+
dat <- data_frame0(x = c(1:2, 1:2 + 0.1), y = 1,
31+
PANEL = factor(rep(1:2, each = 2)))
32+
33+
layer <- geom_bar()
34+
params <- layer$geom_params
35+
36+
# Default should be panel-wise resolution (0.9), not data-wise resolution (0.1)
37+
new <- layer$geom$setup_data(dat, params)
38+
expect_equal(
39+
new$xmax - new$xmin,
40+
rep(0.9, 4)
41+
)
42+
43+
# Check that default can still be overridden
44+
params$width <- 0.5
45+
new <- layer$geom$setup_data(dat, params)
46+
expect_equal(
47+
new$xmax - new$xmin,
48+
rep(0.5, 4)
49+
)
50+
})

0 commit comments

Comments
 (0)