I am having difficulty aligning my grid figure correctly when I have removed the repeating tick labels on the y-axis while combining other facet wraps with different length tick labels in patchwork. I have prepared an example to demonstrate the problem I am currently having.
library(ggh4x, warn.conflicts = F)
#> Lade nötiges Paket: ggplot2
library(ggplot2, warn.conflicts = F)
library(dplyr, warn.conflicts = F)
library(patchwork, warn.conflicts = F)
# trim_blank is working
trimmed_1 <- mpg %>%
mutate(class = factor(class)) %>%
filter(class == c("2seater", "compact", "midsize")) %>%
ggplot(aes(displ, hwy * 1000)) +
geom_point() +
facet_wrap2(vars(class), axes = "x", remove_labels = "all", trim_blank = T)
# trim_blank is not working
untrimmed_1 <- mpg %>%
mutate(class = factor(class)) %>%
filter(class == c("2seater", "compact", "midsize")) %>%
ggplot(aes(displ, hwy * 1000)) +
geom_point() +
facet_wrap2(vars(class), axes = "all", remove_labels = "all", trim_blank = T)
# trim_blank is working
trimmed_2 <- mpg %>%
mutate(class = factor(cyl)) %>%
filter(class == c("4", "6", "8")) %>%
ggplot(aes(displ, log(cty))) +
geom_point() +
facet_wrap2(vars(cyl), axes = "x", remove_labels = "all", trim_blank = T)
# trim_blank is not working
untrimmed_2 <- mpg %>%
mutate(class = factor(cyl)) %>%
filter(class == c("4", "6", "8")) %>%
ggplot(aes(displ, log(cty))) +
geom_point() +
facet_wrap2(vars(cyl), axes = "all", remove_labels = "all", trim_blank = T)
(trimmed_1 / trimmed_2) # plots are aligned
(untrimmed_1 / untrimmed_2) # plots are not horizontally aligned
Created on 2024-03-24 with reprex v2.1.0
Not sure what you expect from trim_blank
. According to the docs
When TRUE (default), does not draw rows and columns containing no panels. When FALSE, the nrow and ncol arguments are taken literally, even when there are more than needed to fit all panels.
But to fix your issue with the alignment you can use ggplot2::facet_wrap
instead of ggh4x::facet_wrap2
which in ggplot2 3.5.0
gained some of the functionalities from ggh4x
, i.e. facet_wrap
now has an axes=
and an axis.labels=
argument. And as a side-effect works fine when aligning the plots using patchwork
:
library(ggplot2, warn.conflicts = F)
library(dplyr, warn.conflicts = F)
library(patchwork, warn.conflicts = F)
packageVersion("ggplot2")
#> [1] '3.5.0'
packageVersion("patchwork")
#> [1] '1.2.0'
untrimmed_1 <- mpg %>%
mutate(class = factor(class)) %>%
filter(class == c("2seater", "compact", "midsize")) %>%
ggplot(aes(displ, hwy * 1000)) +
geom_point() +
facet_wrap(vars(class), axes = "all", axis.labels = "all_x")
untrimmed_2 <- mpg %>%
mutate(class = factor(cyl)) %>%
filter(class == c("4", "6", "8")) %>%
ggplot(aes(displ, log(cty))) +
geom_point() +
facet_wrap(vars(cyl), axes = "all", axis.labels = "all_x")
untrimmed_1 / untrimmed_2 # plots are aligned