这是我的代码:
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 行。
有什么帮助吗?
uj5u.com热心网友回复:
这对于拼凑包来说是相当直接的。永远不要忘记 facet 选项 - 为此,您需要 ggh4x 包(见下文)。
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
)
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
.
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
)
#This resembles the patchwork idea, but it takes 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)
uj5u.com热心网友回复:
您可能会发现使用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)))
结果:
0 评论