Skip to content

Commit f5782ff

Browse files
authored
facet_grid() evaluates facets before adding margins (#5944)
* evaluate facets before adding margins * add test * add news bullet
1 parent 98f5e12 commit f5782ff

File tree

3 files changed

+20
-5
lines changed

3 files changed

+20
-5
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+
* Fixed bug in `facet_grid(margins = TRUE)` when using expresssions
4+
(@teunbrand, #1864).
35
* `geom_step()` now supports the `orientation` argument (@teunbrand, #5936).
46
* `position_dodge()` and `position_jitterdodge()` now have a `reverse` argument
57
(@teunbrand, #3610)

R/facet-grid-.R

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -297,12 +297,21 @@ FacetGrid <- ggproto("FacetGrid", Facet,
297297
return(data)
298298
}
299299

300-
# Compute faceting values and add margins
301-
margin_vars <- list(intersect(names(rows), names(data)),
302-
intersect(names(cols), names(data)))
303-
data <- reshape_add_margins(data, margin_vars, params$margins)
304-
300+
# Compute faceting values
305301
facet_vals <- eval_facets(c(rows, cols), data, params$.possible_columns)
302+
if (nrow(facet_vals) == nrow(data)) {
303+
# Margins are computed on evaluated faceting values (#1864).
304+
facet_vals <- reshape_add_margins(
305+
# We add an index column to track data recycling
306+
vec_cbind(facet_vals, .index = seq_len(nrow(facet_vals))),
307+
list(intersect(names(rows), names(facet_vals)),
308+
intersect(names(cols), names(facet_vals))),
309+
params$margins
310+
)
311+
# Apply recycling on original data to fit margins
312+
data <- vec_slice(data, facet_vals$.index)
313+
facet_vals$.index <- NULL
314+
}
306315

307316
# If any faceting variables are missing, add them in by
308317
# duplicating the data

tests/testthat/test-facet-map.R

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ test_that("margins add extra data", {
2222
loc <- panel_map_one(facet_grid(a~b, margins = "b"), df)
2323

2424
expect_equal(nrow(loc), nrow(df) * 2)
25+
26+
# For variables including computation (#1864)
27+
loc <- panel_map_one(facet_grid(a ~ I(b + 1), margins = TRUE), df)
28+
expect_equal(nrow(loc), nrow(df) * 4)
2529
})
2630

2731
test_that("grid: missing facet columns are duplicated", {

0 commit comments

Comments
 (0)