常用的拼图包:par()中的mfrow、grid.arrange、cowplot、customLayout、patchwork等等
其中最方便快捷且功能强大的是patchwork
官网:https://patchwork.data-imaginist.com/index.html
patchwork的功能和优点:
(1)支持直接p1+p2拼图,比任何一个包都简单
(2)复杂的布局代码易读性更强
(3)可以给子图添加标记(例如ABCD, I II III IV 这样)
(4)可以统一修改所有子图
(5)可以将子图的图例移到一起,整体性特别好
⚠️:patchwork仅支持ggplot2的拼图
1基础用法(拼两张图)
图形准备
library(ggplot2)
p1 <- ggplot(mtcars) +
geom_point(aes(mpg, disp)) +
ggtitle('Plot 1')
p2 <- ggplot(mtcars) +
geom_boxplot(aes(gear, disp, group = gear)) +
ggtitle('Plot 2')
p3 <- ggplot(mtcars) +
geom_point(aes(hp, wt, colour = mpg)) +
ggtitle('Plot 3')
p4 <- ggplot(mtcars) +
geom_bar(aes(gear)) +
facet_wrap(~cyl) +
ggtitle('Plot 4')
横着拼就"|"或"+",竖着拼就"/"
p1 + p2
p1 / p2
2 拼多张图(layout设置)
默认情况下,patchwork会是拼的图呈方形,并按行排列。
p1 + p2 + p3 + p4
- 2.1 plot_layout()
上面的设定可以通过额外传入plot_layout()函数来改变(继承了矩阵的两个参数”nrow“和"byrow")。
p1 + p2 + p3 + p4 + plot_layout(nrow = 3, byrow = FALSE)
- 2.2 直接用小括号也可以
p1 | (p2 / p3)
(p1 | p2) /p3
- 2.3 layout不用坐标,不用宽高比例,直接用ABCD就行
layout <- '
ABB
CCD
'
# 上面的代码等于layout <- 'ABB\n CCD'
p1 + p2 + p3 + p4 + plot_layout(design = layout)
- 2.4 拼非ggplot内容
p1 + grid::textGrob('Some really important text')
更多布局设置,参考:https://patchwork.data-imaginist.com/articles/guides/layout.html
3修改图形
当进行拼图时,后一个图是active的,可以接受新的ggplot2对象比如geoms,labels等
p1 + p2 + labs(subtitle = 'This will appear in the last plot')
p1 + p2 + geom_jitter(aes(gear, disp))
patchwork <- p1 + p2
patchwork[[1]] <- patchwork[[1]] + theme_minimal()
patchwork
4 图形标题设置
通过额外传入plot_annotation()参数来设置
patchwork <- (p1 + p2) / p3
patchwork + plot_annotation(
title = 'The surprising truth about mtcars',
subtitle = 'These 3 plots will reveal yet-untold secrets about our beloved data-set',
caption = 'Disclaimer: None of these plots are insightful'
)
patchwork还可以自动标记。(拉丁字母,阿拉伯数字,罗马数字都可以。)
p1 + p2 + p3 +
plot_annotation(tag_levels = 'I')
patchwork + plot_annotation(tag_levels = 'A')
设置字体大小
patchwork +
plot_annotation(tag_levels = 'A') &
theme(plot.tag = element_text(size = 8))
patchwork[[1]] <- patchwork[[1]] + plot_layout(tag_level = 'new')
patchwork + plot_annotation(tag_levels = c('A', '1'))
5. 统一修改所有子图(&符号)
patchwork <- p3 / (p1 | p2)
patchwork & theme_minimal()