Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

facet_grid() evaluates facets before adding margins #5944

Merged
merged 4 commits into from
Jul 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# ggplot2 (development version)

* Fixed bug in `facet_grid(margins = TRUE)` when using expresssions
(@teunbrand, #1864).
* `geom_step()` now supports the `orientation` argument (@teunbrand, #5936).
* `position_dodge()` and `position_jitterdodge()` now have a `reverse` argument
(@teunbrand, #3610)
Expand Down
19 changes: 14 additions & 5 deletions R/facet-grid-.R
Original file line number Diff line number Diff line change
Expand Up @@ -297,12 +297,21 @@ FacetGrid <- ggproto("FacetGrid", Facet,
return(data)
}

# Compute faceting values and add margins
margin_vars <- list(intersect(names(rows), names(data)),
intersect(names(cols), names(data)))
data <- reshape_add_margins(data, margin_vars, params$margins)

# Compute faceting values
facet_vals <- eval_facets(c(rows, cols), data, params$.possible_columns)
if (nrow(facet_vals) == nrow(data)) {
# Margins are computed on evaluated faceting values (#1864).
facet_vals <- reshape_add_margins(
# We add an index column to track data recycling
vec_cbind(facet_vals, .index = seq_len(nrow(facet_vals))),
list(intersect(names(rows), names(facet_vals)),
intersect(names(cols), names(facet_vals))),
params$margins
)
# Apply recycling on original data to fit margins
data <- vec_slice(data, facet_vals$.index)
facet_vals$.index <- NULL
}

# If any faceting variables are missing, add them in by
# duplicating the data
Expand Down
4 changes: 4 additions & 0 deletions tests/testthat/test-facet-map.R
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ test_that("margins add extra data", {
loc <- panel_map_one(facet_grid(a~b, margins = "b"), df)

expect_equal(nrow(loc), nrow(df) * 2)

# For variables including computation (#1864)
loc <- panel_map_one(facet_grid(a ~ I(b + 1), margins = TRUE), df)
expect_equal(nrow(loc), nrow(df) * 4)
})

test_that("grid: missing facet columns are duplicated", {
Expand Down
Loading