library(ggplot2)
if (requireNamespace("patchwork", quietly = TRUE)) {
library(patchwork)
# Two plots stacked vertically - x-axis is duplicated
p1 <- ggplot(mtcars, aes(mpg, wt, color = factor(cyl))) +
geom_point() +
labs(y = "Weight")
p2 <- ggplot(mtcars, aes(mpg, hp, color = factor(cyl))) +
geom_point() +
labs(y = "Horsepower")
# Without collect_axes: both plots show x-axis
p1 / p2
# With collect_axes: removes redundant x-axis from top plot
collect_axes(p1 / p2)
# Keep separate legends
collect_axes(p1 / p2, guides = "keep")
}
Run the code above in your browser using DataLab