Description
It makes sense that it’s not possible to mix facet_grid(..., scales = "free", space = "free")
with coord_fixed()
in most situations. However, I think that it should be possible and makes sense to allow this when both, x and y, scales are discrete.
For example, a use case in this reprex with ggplot2
version 3.3.4:
library(tidyverse) # with ggplot2 v3.3.4
set.seed(1)
df <- expand_grid(x = letters[1:6], y = LETTERS[1:2]) %>%
mutate(w = case_when(x %in% letters[1:2] ~ "1",
x %in% letters[3:6] ~ "2")) %>%
mutate(value = rnorm(6*2))
gg <- ggplot(df) +
geom_point(aes(x, y, color = value)) +
facet_grid(cols = vars(w), scales = "free", space = "free")
gg
Here, we have different numbers and levels of factors in x scale, so it’s necessary to use scales = "free"
and space = "free"
for efficient use of space.
When I make plots like this one, I like to make sure that the breaks on x and y axes are placed equidistantly (so the background grid is made of squares), which would generally be accomplished with coord_fixed()
but not possible in this case since we are using free scales and space.
gg + coord_fixed()
#> Error: coord_fixed doesn't support free scales
As of version 3.3.3 of ggplot2
it was possible to still accomplish this without coord_fixed()
by the (perhaps hacky and off-label) use of theme(aspect.ratio = 1)
, also pointed out in this SO post. See reprex below with version 3.3.3. This is however no longer possible since this bug was fixed (#4432).
library(tidyverse) # with ggplot2 v3.3.3
set.seed(1)
df <- expand_grid(x = letters[1:6], y = LETTERS[1:2]) %>%
mutate(w = case_when(x %in% letters[1:2] ~ "1",
x %in% letters[3:6] ~ "2")) %>%
mutate(value = rnorm(6*2))
gg <- ggplot(df) +
geom_point(aes(x, y, color = value)) +
facet_grid(cols = vars(w), scales = "free", space = "free")
gg + theme(aspect.ratio = 1)
It would be great if this can be accomplished legitimately with coord_fixed()
rather than by using hacks. Based on my admittedly superficial understanding, I think that the use of coord_fixed()
when faceting with free scales and space should be legitimate as long as the x and y scales are discrete.
Created on 2021-08-12 by the reprex package (v2.0.0)