teunbrand / ggh4x

ggplot extension: options for tailored facets, multiple colourscales and miscellaneous
https://teunbrand.github.io/ggh4x/
Other
534 stars 32 forks source link

`facet_nested()` adds "phantom" panels if there are nested facets. #116

Closed eliocamp closed 11 months ago

eliocamp commented 11 months ago

Trying to solve other issues I found that facet_nested() behaves strangely in specific case.

I'm trying to plot data belonging to a category as "reference" data in every panel and without getting a panel of its own. This seems to work:

library(ggplot2)

base <- ggplot(mapping = aes(mpg, disp)) +
  geom_point(data = subset(mtcars, cyl != 4)) +
  geom_point(data = subset(mtcars, cyl == 4) |> 
               transform(cyl = NULL), 
             color = "gray") 

base +
  ggh4x::facet_nested(am ~ cyl)

Which is similar to ggplot2sfacet_grid()`.

base +
  facet_grid(am ~ cyl)

But if I add a nested facet, the "reference" data is moved to its own panel:

base +
  ggh4x::facet_nested(am ~ cyl + vs)

And note that this is not what ggplot2 does in this case

base +
  facet_grid(am ~ cyl + vs)

(Although note that ggplot2 does draw phantom panels if one uses a global data (see: https://github.com/tidyverse/ggplot2/issues/5356) although it draws the value of the facet, which ggh4x doesn't do.)

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

teunbrand commented 11 months ago

I'm doing this on purpose in nested facets, which is described in the details of ?facet_nested():

Unlike facet_grid(), this function only automatically expands missing variables when they have no variables in that direction, to allow for unnested variables. It still requires at least one layer to have all faceting variables.

The reason why this might be desirable is explained here.

To have the default facet_grid() behaviour, you can use the following:

library(ggplot2)
library(ggh4x)

base <- ggplot(mapping = aes(mpg, disp)) +
  geom_point(data = subset(mtcars, cyl != 4)) +
  geom_point(data = subset(mtcars, cyl == 4) |> 
               transform(cyl = NULL), 
             color = "gray") 
base +
  facet_grid2(am ~ cyl + vs, strip = strip_nested())

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

teunbrand commented 11 months ago

I'm going to close this because this is by design and viable workarounds are available.