patchwork 是 ggplot2 生态系统中最强大的图形组合工具,它能智能地对齐图表轴线。
合并总结
只有纵向/横向排布
# 横向排布
p1 + p2 +
plot_layout(
widths = c(3,1),
guides = "collect"
)
# 纵向排布
p1 / p2 +
plot_layout(
heights = c(3,1),
guides = "collect"
)
横纵混合排布
假设有p1, p2, p3, p4四个子图,按照上2下2,左右排布,则可以:
p1 + p2 + p3 + p4 + # 假设 p1-p4 是你的四个图/占位符
plot_layout(
heighs = c(1,3),
widths = c(3,1), # 定义了三列的宽度比例
design = "
12 # 指第一个图和第二个图,第一行
34 # 指第三个图和第四个图,第二行
"
)
Gemini回答横纵混合排布 (p1+p2) / (p3+p4) + plot_layout(),这样的嵌套写法,会导致宽度控制异常,stackflow里有相关问题的解释: https://stackoverflow.com/questions/65320638/controlling-widths-of-many-patchworked-ggplots
plot_spacer占位
当有一个主图,p_main,和横轴的一个附图p_x,和纵轴的附图p_y,将三者放到一起时,会有一块是空着的,这个时候,就需要plot_spacer() 填充占位:
p_x + plot_spacer() + p_main + p_y +
plot_layout(
heighs = c(1,3)
widths = c(3,1),
design = "
12
34
"
)
示例来自Gemini
1. 准备数据和绘图
library(ggplot2)
library(patchwork)
library(dplyr)
# 假设数据:模拟你的平均值和Y轴变量
set.seed(42)
data_with_avg <- tibble(
average_IncLevel1 = rnorm(100, mean = 20, sd = 5),
some_y_variable = runif(100, 10, 50)
)
# --- 绘制两个独立的图表 ---
# 1. 散点图 (Scatter Plot) - 放在顶部
p_scatter <- ggplot(data_with_avg, aes(x = average_IncLevel1, y = some_y_variable)) +
geom_point(alpha = 0.6, color = "darkblue") +
labs(y = "Y Variable", title = "Scatter Plot and Distribution") +
# 移除X轴标题和刻度,因为要和下面的图共用
theme_classic() +
theme(
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank()
)
# 2. 直方图 (Histogram) - 放在底部
p_hist <- ggplot(data_with_avg, aes(x = average_IncLevel1)) +
geom_histogram(bins = 20, fill = "lightblue", color = "black") +
labs(y = "Count", x = "Average IncLevel1") +
theme_classic() +
# 确保底部图保留X轴标题和刻度
theme(
axis.title.x = element_text(vjust = -1), # 稍微下移,避免和图表紧贴
plot.margin = margin(t = 0, r = 5.5, b = 5.5, l = 5.5) # 调整边距
)
2. 使用 patchwork 合并图表
# 使用 / 运算符将图表堆叠起来
# plot_layout(heights = c(3, 1)) 设置了两个图的高度比例 (例如 散点图占3/4,直方图占1/4)
combined_plot <- p_scatter / p_hist +
plot_layout(heights = c(3, 1))
# 打印最终合并的图表
print(combined_plot)