相比R语言基础绘图函数,我更喜欢使用ggplot绘制的图形。而
patchwork
包是一个非常友好的,支持ggplot2对象拼图的工具包。操作简单,高效,nice~
参考官方教程:https://patchwork.data-imaginist.com/index.html
0、安装包以及绘制示例图
# #install.packages("devtools")
# devtools::install_github("thomasp85/patchwork")
library(ggplot2)
library(patchwork)
p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
p3 <- ggplot(mtcars) + geom_bar(aes(gear)) + facet_wrap(~cyl)
p4 <- ggplot(mtcars) + geom_bar(aes(carb))
p5 <- ggplot(mtcars) + geom_violin(aes(cyl, mpg, group = cyl))
1、直接拼图方法
patchwork
包提供有两种方式可供选择
(1)符号连接:+
或者|
均表示左右拼接,/
表示上下拼接,()
可以用于调整优先级
(2)函数调用:wrap_plots()
1.1 简单两张图
p1 + p2 #左右
wrap_plots(p1, p2)

p1 / p2 #上下
wrap_plots(p1, p2, ncol = 1)
1.2 复杂布局
(1)符号连接方式可以通过()
调整优先级
(p1 | p2) / p3 #先左右再上下

p1 | (p2 / p3) #先上下再左右
(2)函数调用方式可通过设置design=
参数,进行复杂布局
- 有点类似基础绘图拼图的
layout()
函数
design <- "AB
CC"
wrap_plots(A = p1, B = p2, C = p3,
design = design)

design <- "AAD
BCE"
wrap_plots(B = p1, A = p2, C = p3, D = p4, E = p5,
design = design)

- 与上图等价的符号连接方式拼图代码如下。可见在更加复杂拼图需求时,还是使用函数调用方式更方便一点。
((p2 + p4) + plot_layout(widths = c(2, 1))) / (p1 + p3 + p5)
2、拼图细节调整
2.1 plot_layout
调整长宽比例
p1 + p2 + plot_layout(widths = c(3,2))
wrap_plots(p1, p2) + plot_layout(widths = c(3,2))

(((p1 / p2) + plot_layout(heights = c(1,2))) | p3) + plot_layout(widths = c(2,1))

2.2 plot_layout
公用图形legend
data(Salaries, package="carData")
p11 <- ggplot(Salaries, aes(x=rank, fill=sex)) +
geom_bar(position="stack") + labs(title='position="stack"')
p22 <- ggplot(Salaries, aes(x=rank, fill=sex)) +
geom_bar(position="dodge") + labs(title='position="dodge"')
p33 <- ggplot(Salaries, aes(x=rank, fill=sex)) +
geom_bar(position="fill") + labs(title='position="fill"')
p11 + p22 + p33 + plot_layout(guides = 'collect')

2.3 plot_annotation
设置总图的title
(p1 | (p2 / p3)) + 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')

2.4 plot_annotation
设置子图的tag标签
(p1 | (p2 / p3)) +
plot_annotation(tag_levels = 'A')
# tag_levels : 'a', 'A', '1', 'i, or 'I'

# tag标签加前缀
((p1 | p2) / p3) +
plot_annotation(tag_levels = 'A', tag_prefix = 'Fig. ')
# tag标签加后缀
((p1 | p2) / p3) +
plot_annotation(tag_levels = 'A', tag_suffix = ':')
- 此外如果想要加个性化的标签,可以在绘制子图时单独添加tag
p1 + labs(tag = "any")
3、ggplot对象与其它对象的拼图
3.1 ggplot对象 + 表格
df = mtcars[1:10, c('mpg', 'disp')]
p1 + gridExtra::tableGrob(df)

3.2 ggplot对象 + 基础绘图
p1 + ~plot(mtcars$mpg, mtcars$disp, main = 'Plot 2')

网友评论