diff --git a/NEWS.md b/NEWS.md index 972070ddf7..1c4a497f4b 100644 --- a/NEWS.md +++ b/NEWS.md @@ -28,6 +28,9 @@ installed, which will offer to install the package before continuing (#4375, @malcolmbarrett) +* Improved error with hint when piping a `ggplot` object into a facet function + (#4379, @mitchelloharawild). + # ggplot2 3.3.3 This is a small patch release mainly intended to address changes in R and CRAN. It further changes the licensing model of ggplot2 to an MIT license. diff --git a/R/facet-.r b/R/facet-.r index a7b852ae11..003a6c8020 100644 --- a/R/facet-.r +++ b/R/facet-.r @@ -276,9 +276,7 @@ df.grid <- function(a, b) { # facetting variables. as_facets_list <- function(x) { - if (inherits(x, "uneval")) { - abort("Please use `vars()` to supply facet variables") - } + x <- validate_facets(x) if (is_quosures(x)) { x <- quos_auto_name(x) return(list(x)) @@ -315,6 +313,19 @@ as_facets_list <- function(x) { x } +validate_facets <- function(x) { + if (inherits(x, "uneval")) { + abort("Please use `vars()` to supply facet variables") + } + if (inherits(x, "ggplot")) { + abort( + "Please use `vars()` to supply facet variables\nDid you use %>% instead of +?" + ) + } + x +} + + # Flatten a list of quosures objects to a quosures object, and compact it compact_facets <- function(x) { x <- flatten_if(x, is_list) diff --git a/R/facet-grid-.r b/R/facet-grid-.r index 4bdb4e137a..0c976e3d35 100644 --- a/R/facet-grid-.r +++ b/R/facet-grid-.r @@ -157,7 +157,14 @@ grid_as_facets_list <- function(rows, cols) { is_rows_vars <- is.null(rows) || is_quosures(rows) if (!is_rows_vars) { if (!is.null(cols)) { - abort("`rows` must be `NULL` or a `vars()` list if `cols` is a `vars()` list") + msg <- "`rows` must be `NULL` or a `vars()` list if `cols` is a `vars()` list" + if(inherits(rows, "ggplot")) { + msg <- paste0( + msg, "\n", + "Did you use %>% instead of +?" + ) + } + abort(msg) } # For backward-compatibility facets_list <- as_facets_list(rows) diff --git a/R/facet-wrap.r b/R/facet-wrap.r index 05fbdd29a0..47bf1f471f 100644 --- a/R/facet-wrap.r +++ b/R/facet-wrap.r @@ -86,6 +86,13 @@ facet_wrap <- function(facets, nrow = NULL, ncol = NULL, scales = "fixed", x = any(scales %in% c("free_x", "free")), y = any(scales %in% c("free_y", "free")) ) + + # Check for deprecated labellers + labeller <- check_labeller(labeller) + + # Flatten all facets dimensions into a single one + facets <- wrap_as_facets_list(facets) + if (!is.null(switch)) { .Deprecated("strip.position", old = "switch") strip.position <- if (switch == "x") "bottom" else "left" @@ -102,12 +109,6 @@ facet_wrap <- function(facets, nrow = NULL, ncol = NULL, scales = "fixed", ncol <- sanitise_dim(ncol) } - # Check for deprecated labellers - labeller <- check_labeller(labeller) - - # Flatten all facets dimensions into a single one - facets <- wrap_as_facets_list(facets) - ggproto(NULL, FacetWrap, shrink = shrink, params = list(