在R中使用cowplot制作ggplot图表占据连续两行

Using cowplot in R to make a ggplot chart occupy two consecutive rows

这是我的代码:

library(ggplot2)
library(cowplot)


df <- data.frame(
  x = 1:10, y1 = 1:10, y2 = (1:10)^2, y3 = (1:10)^3, y4 = (1:10)^4
)

p1 <- ggplot(df, aes(x, y1)) + geom_point()
p2 <- ggplot(df, aes(x, y2)) + geom_point()
p3 <- ggplot(df, aes(x, y3)) + geom_point()
p4 <- ggplot(df, aes(x, y4)) + geom_point()
p5 <- ggplot(df, aes(x, y3)) + geom_point()
# simple grid
plot_grid(p1, p2, 
          p3, p4,
          p5, p4)

但我不想重复 p4 我想“拉伸”p4 以占据 col2 和第 2 行和第 3 行。

有什么帮助吗?

您可能会发现使用 gridExtra::grid.arrange() 更容易。

library(gridExtra)

grid.arrange(p1, p2, p3, p4, p5, 
             ncol = 2, 
             layout_matrix = cbind(c(1,3,5), c(2,4,4)))

结果:

拼凑包非常简单。

另外,永远不要忘记 facet 选项——为此你需要 ggh4x 包。

最后,也是所需的 cowplot 解决方案,它需要多个 plot_grid 对象的复杂嵌套。不是我最喜欢的。

## Option 1 - patchwork 

library(ggplot2)
library(patchwork)

df <- data.frame(
  x = 1:10, y1 = 1:10, y2 = (1:10)^2, y3 = (1:10)^3, y4 = (1:10)^4
)
## patchwork allows working with lists, which I find neat. 
make_p <- function(y){
  ggplot(df, aes(x, !!sym(y))) + geom_point()
}

## custom layout grid
layout <- "
AB
CD
ED
"

ls_p <- lapply(paste0("y", c(1:4,3)), make_p)

wrap_plots(ls_p) + plot_layout(design = layout)

在您的特定示例中,另一种选择是利用 ggh4x::facet_manual

## Option 2 - faceting with ggh4x
library(tidyverse)
library(ggh4x)

df <- data.frame(
  x = 1:10, y1 = 1:10, y2 = (1:10)^2, y3 = (1:10)^3, y4 = (1:10)^4,
  ## adding y5 for simplicity
  y5 = (1:10)^3
)

design <- "
AB
CD
ED
"
## or you can pass a matrix as design argument
# design <- matrix(c(1,2,3,4,5,4), 3, 2, byrow = TRUE)

df %>% 
  pivot_longer(matches("^y")) %>%
  ggplot(aes(x, value)) + 
  geom_point() +
  facet_manual(~ name, design)

最后,cowplot 选项。

## option 3 nesting plot_grids with cowplot
library(cowplot)
p1 <- ggplot(df, aes(x, y1)) + geom_point()
p2 <- ggplot(df, aes(x, y2)) + geom_point()
p3 <- ggplot(df, aes(x, y3)) + geom_point()
p4 <- ggplot(df, aes(x, y4)) + geom_point()
p5 <- ggplot(df, aes(x, y3)) + geom_point()

top_row <- plot_grid(p1, p2)
left_col <- plot_grid(p3, p5, ncol = 1)
bottom_panel <- plot_grid(left_col, p4, ncol = 2)

plot_grid(top_row, bottom_panel, ncol = 1)