ggplot2 icon indicating copy to clipboard operation
ggplot2 copied to clipboard

Axis alignment over multiple panels

Open teunbrand opened this issue 3 months ago • 3 comments

This is a proof-of-concept PR exploring to fix #5820.

Briefly, this PR adds extra spacers to the axis gtable that have 'null' units so that the spacers take up the 'available' space. This works to align labels across panels as 'available space' is flexible and adapts to the size of the cell in the plot's gtable, which is always* based on the largest axis.

* See caveat below

devtools::load_all("~/packages/ggplot2")
#> ℹ Loading ggplot2

data.frame(
  F = c(rep("F1", 3), rep("F2", 3)),
  Y = c("AAAAAAAAAAAAAAAAAAA", "BBBBB", "CCCCCCCCC", "DDDDD", "EEEEEEEE", "FFF"),
  Cnt = c(10, 20, 30, 50, 40 ,60)
) |>
  ggplot(mapping = aes(y = Y, x = Cnt)) +
  geom_col() +
  facet_grid(
    rows = vars(F),
    scales = "free_y"
  ) +
  theme(
    axis.text.y = element_text(hjust = 0)
  )

I consider this PR a POC because this solution is not perfect. In some circumstances, the plot's gtable cell size allocated to axes is smaller than the actual axis size, in particular when facet_wrap() has ragged panels that need to be labelled on the ragged ends. In the plot below, notice that the right axis of the bottom-middle panel is misplaced and also the bottom axis of the top-right panel is misplaced.

# The only failing unit test is this plot
ggplot(mtcars, aes(mpg, disp)) +
  geom_point() +
  guides(x = "axis", y = "axis", x.sec = "axis", y.sec = "axis") + 
  facet_wrap(vars(cyl, vs), axes = "all", axis.labels = "margins")

Created on 2024-04-04 with reprex v2.1.0

However, the axis doesn't know when it will be placed in smaller cells and installing the plumbing to let the axis know would require tempering with already very complicated code that places back axes. Unless I can find some trick to mitigate this problem, I'm stuck at this 90% solution, which is why I wouldn't merge this PR for now.

teunbrand avatar Apr 04 '24 14:04 teunbrand