Skip to content

Facets use nonexistent values if removed from inside geoms.  #5356

Closed as not planned
@eliocamp

Description

@eliocamp

facet_wrap() (and facet_grid()) seem to draw panels for values that are not drawn if they are removed using the data argument in a geom.

So, this draws a panel for cyl = 4 even though that data doesn't exist in the plot.

library(ggplot2)

ggplot(mtcars, aes(mpg, disp)) +
  geom_point(data = \(x) subset(x, cyl != 4)) +
  facet_wrap(~cyl, drop = TRUE)

Compare with the result removing the category at the top-level call of the plot.

mtcars |> 
  subset(cyl != 4) |> 
  ggplot(aes(mpg, disp)) +
  geom_point() +
  facet_wrap(~cyl, drop = TRUE)

The use case for this is to use one of the categories as the reference and draw it in every panel, but I don't want it to have its own panel. So my though was to plot one geom without the reference category and then another with just the reference and without the faceting variable. But it doesn't work because it adds the panel for the reference category even though that category is never seen by any geom.

ggplot(mtcars, aes(mpg, disp)) +
  geom_point(data = \(x) subset(x, cyl != 4)) +
  geom_point(data = \(x) subset(x, cyl == 4) |> 
               transform(cyl = NULL), 
             color = "gray") +
  facet_wrap(~cyl, drop = TRUE)

Created on 2023-07-19 with reprex v2.0.2

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions