简介
tidyverse可以说是追求代码“易读”的典范,今天介绍的拼图包名为“ patchwork”,作者是tidyverse团队成员-- Thomas Lin Pedersen,
长得帅的大佬可以拥有寄几的大照,虽然是黑白的:
博客地址:https://www.data-imaginist.com/2019/patch-it-up-and-send-it-out/
patchwork包官方教程https://patchwork.data-imaginist.com/index.html
总结一下他的功能和优点:
(1)支持直接p1+p2拼图,比任何一个包都简单
(2)复杂的布局代码易读性更强
(3)可以给子图添加标记(例如ABCD, I II III IV 这样)
(4)可以统一修改所有子图
(5)可以将子图的图例移到一起,整体性特别好
简单好用,功能强大,真香!
1.极简入门-拼两张图
横着就"+",竖着就"/"
library(ggplot2)
library(patchwork)
p1 <- ggplot(mpg) +
geom_point(aes(hwy, displ))
p2 <- ggplot(mpg) +
geom_bar(aes(manufacturer, fill = stat(count))) +
coord_flip
就是这么优秀:
p1 + p2
p1 / p2
2.多几张图p3 <- ggplot(mpg) +
geom_smooth(aes(hwy, cty)) +
facet_wrap(~year)
p1 + p2 + p3
> geom_smooth
using method = 'loess' and formula 'y ~ x'
p4 <- ggplot(mpg) +
geom_tile(aes(factor(cyl), drv, fill = stat(count)), stat = 'bin2d')
p1 + p2 + p3 + p4
> geom_smooth
using method = 'loess' and formula 'y ~ x'
继承了矩阵的两个参数”nrow“和"byrow"
p1 + p2 + p3 + p4 + plot_layout(nrow = 4)
> geom_smooth
using method = 'loess' and formula 'y ~ x'
再难一点也不在话下
(p1 | p2) /
p3
> geom_smooth
using method = 'loess' and formula 'y ~ x'
p1 | (p2 / p3)
> geom_smooth
using method = 'loess' and formula 'y ~ x'
(p1 | (p2 / p3)) +
plot_annotation(title = 'The surprising story about mtcars')
> geom_smooth
using method = 'loess' and formula 'y ~ x'
3.可以再复杂一点
大招:layout不用坐标,不用宽高比例,直接用ABCD就行
layout <- '
ABB
CCD
'
p1 + p2 + p3 + p4 + plot_layout(design = layout)
> geom_smooth
using method = 'loess' and formula 'y ~ x'
4.给子图添加标记
啥也不说了,大佬怎么就这么优秀呢?
p1 + p2 + p3 +
plot_annotation(tag_levels = 'I')
> geom_smooth
using method = 'loess' and formula 'y ~ x'
patchwork <- (p4 | p2) /
p1
patchwork + plot_annotation(tag_levels = 'A')
嵌套式的子标题也能搞定
patchwork <- ((p4 | p2) + plot_layout(tag_level = 'new')) /
p1
patchwork + plot_annotation(tag_levels = c( 'A', '1'))
5.统一修改所有子图
用”&“符号,简单的很
patchwork & theme_minimal
6.图例管理
走开,图例都给我去右边
patchwork + plot_layout(guides = 'collect')
一样的图例可以只显示一个,但是要让阈值一致
patchwork <- patchwork & scale_fill_continuous(limits = c( 0, 60))
patchwork + plot_layout(guides = 'collect')