安装
因为作者仅仅在GitHub
发布了patchwork,因此无法使用install.packages("patchwork")
从CRAN处获取。为了获取该包,首先应该安装devtools
包,其次在使用如下命令:
1 2 3
| library(devtools) install_github("thomasp85/patchwork")
|
加载数据
使用R自带的mtcars
数据,先使用ggplot2
作图:
1 2 3 4 5 6 7
| library(ggplot2) library(patchwork)
p1 <- ggplot(mtcars, aes(x=mpg, y=disp))+ geom_point() p2 <- ggplot(mtcars, aes(x=gear, y=disp, group = gear))+ geom_boxplot() p3 <- ggplot(mtcars, aes(x=disp, y=qsec))+ geom_smooth() p4 <- ggplot(mtcars, aes(x=carb))+ geom_bar()
|
+ 叠加图

- 子轨道

| 水平布局

/垂直布局

*和& 同一操作应用所有图形
1
| (p1 + (p2 + p3) + p4 + plot_layout(ncol = 1)) * theme_bw()
|

1
| (p1 + (p2 + p3) + p4 + plot_layout(ncol = 1)) & theme_bw()
|

{} 或者 () 嵌套布局图形
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| p1 + { p2 + { p3 + p4 + plot_layout(ncol=1) } } + plot_layout(ncol=1)
p1 + ( p2 + ( p3 + p4 + plot_layout(ncol=1) ) ) + plot_layout(ncol=1)
|

plot_layout 调节拼接细节
1
| p1 + p2 + plot_layout(ncol = 1, heights = c(2, 1))
|

plot_spacer 添加空白

plot_annotation 设置title,subtitles 和 captions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 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', 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'))
patchwork + plot_annotation(tag_levels = c('A', '1'), tag_prefix = 'Fig. ', tag_sep = '.', tag_suffix = ':')
|

控制legend
1 2 3 4 5 6 7 8 9
| p1 <- ggplot(mtcars, aes(x=mpg, y=disp, colour = mpg, size = wt))+ geom_point() p2 <- ggplot(mtcars %>% mutate(gear=factor(gear)), aes(x=gear, y=disp, group = gear, color = gear))+ geom_boxplot()
(p3 | (p1 / p2)) + plot_layout(guides = 'collect') + guide_area()
|

总结
与cowplot
包相比,patchwork
包更适合基于ggplot2的产生的图形,它的布局更加简洁,语法简单
引用
- patchwork
- patchwork拼图
参考文章如引起任何侵权问题,可以与我联系,谢谢。