簡介
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
總結(jié)一下他的功能和優(yōu)點:
(1)支持直接p1+p2拼圖,比任何一個包都簡單
(2)復(fù)雜的布局代碼易讀性更強
(3)可以給子圖添加標(biāo)記(例如ABCD, I II III IV 這樣)
(4)可以統(tǒng)一修改所有子圖
(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
就是這么優(yōu)秀:
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'

繼承了矩陣的兩個參數(shù)”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.可以再復(fù)雜一點
大招:layout不用坐標(biāo),不用寬高比例,直接用ABCD就行
layout <- '
ABB
CCD
'
p1 + p2 + p3 + p4 + plot_layout(design = layout)
> geom_smooth using method = 'loess' and formula 'y ~ x'

4.給子圖添加標(biāo)記
啥也不說了,大佬怎么就這么優(yōu)秀呢?
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')

嵌套式的子標(biāo)題也能搞定
patchwork <- ((p4 | p2) + plot_layout(tag_level = 'new')) /
p1
patchwork + plot_annotation(tag_levels = c( 'A', '1'))

5.統(tǒng)一修改所有子圖
用”&“符號,簡單的很
patchwork & theme_minimal

6.圖例管理
走開,圖例都給我去右邊
patchwork + plot_layout(guides = 'collect')

一樣的圖例可以只顯示一個,但是要讓閾值一致
patchwork <- patchwork & scale_fill_continuous(limits = c( 0, 60))
patchwork + plot_layout(guides = 'collect')
