Reputation: 41
Following codes generate a grid of plots shown in the figure below:
library(tidyverse)
library(cowplot)
p1 <- cars %>%
ggplot(aes(x = speed, y = dist)) +
geom_point() +
theme_bw()
p2 <- cars %>%
ggplot(aes(x = speed, y = dist)) +
geom_point() +
scale_y_continuous(trans = "log2", breaks = c(2, 4, 8, 16, 32, 64, 128),
limits = c(2, 128)) +
annotation_logticks(sides = "l") +
theme_bw()
p3 <- diamonds %>%
ggplot(aes(x = carat, y = price, colour = clarity)) +
geom_point() +
theme_bw() +
theme(legend.position = c(0.8, 0.4))
p4 <- plot_grid(p1, p1, nrow = 2, labels = c("B", "C"))
p5 <- plot_grid(p3, p4, nrow = 2, align = "hv", axis = "lb", rel_heights = c(0.5, 1),
labels = c("A", ""))
p6 <- plot_grid(p1, p2, nrow = 2, align = "h", rel_heights = c(0.5, 1),
labels = c("D", "E"))
p7 <- plot_grid(p5, p6, ncol = 2, align = "b")
p7
I wish to align the bottom axis of (A) with top axes of (B, C) respectively, and align bottom axis of (C) with the bottom axis of (E). This should stretch the (B,C) grid plot across the height of (E) and width of (A). I have tried several alignment options.
I have found queries similar to this problem which allow to either get the width or the height alignment right but not both!
I will also add that this reproducible example is the closest I can get to my actual plot. Here I have managed to align the width with panel (A) but am unable to align the height of (B,C) with (E).
Upvotes: 1
Views: 871
Reputation: 37923
May I suggest to use patchwork instead? I find that it handles the alignment of panels more elegantly than anything else around.
library(tidyverse)
library(cowplot)
p1 <- cars %>%
ggplot(aes(x = speed, y = dist)) +
geom_point() +
theme_bw()
p2 <- cars %>%
ggplot(aes(x = speed, y = dist)) +
geom_point() +
scale_y_continuous(trans = "log2", breaks = c(2, 4, 8, 16, 32, 64, 128),
limits = c(2, 128)) +
annotation_logticks(sides = "l") +
theme_bw()
p3 <- diamonds %>%
ggplot(aes(x = carat, y = price, colour = clarity)) +
geom_point() +
theme_bw() +
theme(legend.position = c(0.8, 0.4))
library(patchwork)
#>
#> Attaching package: 'patchwork'
#> The following object is masked from 'package:cowplot':
#>
#> align_plots
p3 + p1 + p1 + p1 + p2 +
plot_layout(
design = "
AD
BE
CE
"
) +
plot_annotation(tag_levels = "A")
Created on 2022-01-05 by the reprex package (v2.0.1)
Upvotes: 2