尽管patchwork包通过 +,|进行图片拼接非常容易和直观,但是很难以编程方式使用。 接下来介绍{wrap_plots}函数的使用,它是完美的替代解决方案!
library(ggplot2)
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))
wrap_plots(p1, p2, p3, p4, p5)
![](https://img.haomeiwen.com/i16360488/fd0a59096d6e2deb.png)
也可以使用下面这种写法
plots <- list(p1, p2, p3, p4, p5)
wrap_plots(plots)
![](https://img.haomeiwen.com/i16360488/520cae214efc0c3d.png)
将图形名称与区域匹配
design <- "#BB
AA#"
wrap_plots(B = p1, A = p2, design = design)
![](https://img.haomeiwen.com/i16360488/1b04f339d6d38dd9.png)
wrap_plots(p1, p2, design = design)
![](https://img.haomeiwen.com/i16360488/0e4f28d670c6e8a6.png)
design <- "CB
CA"
wrap_plots(A=p2,B=p1,C=p3,design = design)
![](https://img.haomeiwen.com/i16360488/2922403cce31b437.png)
design <- "AB
CC"
wrap_plots(A=p2,B=p1,C=p3,design = design)
![](https://img.haomeiwen.com/i16360488/2e745696817bf24c.png)
合并图例至顶部
p1 <- iris %>%
ggplot(aes(Sepal.Length,Petal.Length,color=Species))+
geom_point()+
theme(legend.direction ="horizontal")
p2 <- iris %>%
ggplot(aes(Petal.Width,Petal.Length,color=Species))+
geom_point()+
theme(legend.direction ="horizontal")
wrap_plots(
guide_area(),p1,p2,
design="AA\nBC",
guides = "collect",
heights=c(1/5,4/5)) +
plot_annotation(tag_levels = "A")
![](https://img.haomeiwen.com/i16360488/84cfd691bd64e771.png)
网友评论