ggplot2绘图:多张图合并为一张

以下内容来自教程

R语言中多张图画到同一个页面上常用的函数为par()layout()
par()函数详解

layout()函数的简单使用

但是这两个函数不适用于ggplot2ggplot2作图如果希望把多张图放到同一个页面上基本的解决办法是使用(The basic solution is to use the gridExtra R package),主要的两个函数为grid.arrange()arrangeGrob();然而这两个函数都有各自的缺点(说明缺点的英文暂时还没有看懂)

  • these functions makes no attempt at aligning the plot panels; instead, the plots are simply placed into the grid as they are, and so the axes are not aligned.

为了解决这个问题,可以使用cowplot这个Rpackage,其中包括一个函数plot_grid();然而这个包也有一个缺点

  • the cowplot package doesn't contain any solution for multi-pages layout

所以就有了ggpubr包中的ggarrange()函数

  • a wrapper around the plot_grid() function(wrapper是什么意思呢?)
  • to arrange multiple ggplots over multiple pages
  • it can also create a common unique legend for multiple plots.
第一步安装

两种方式可以选择

  • 1
    library(devtools)
    install_github("kassambara/ggpubr")
  • 2
    install.packages("ggpubr")
第二步使用ggplot2绘图

使用到的数据是ToothGrowth
data("ToothGrowth")
data("mtcars")

  • 1 箱线图
library(ggplot2)
df_box<-ToothGrowth
df_box$dose<-factor(df_box$dose)
ggplot(data=df_box,aes(x=dose,y=len,group=dose))+
  geom_boxplot()+theme_bw()
p1
6857799-4318821b91012c88.png
Rplot02.png
  • 2 柱形图
    柱形图安装从小到大的顺序往后画,印象里是可以用reorder()函数实现的,但是想不起来怎么用了,刚刚找到了一个教程,reorder是放在aes()中x的位置,reorder第一个参数是排序的因子变量,第二个是数值变量R中排序函数总结:sort,order,rank,arrange,reorder
df_bar<-mtcars
df_bar$name<-row.names(df_bar)
df_bar$name
p2<-ggplot(data=df_bar,aes(x=reorder(name,mpg), y=mpg))+
  geom_bar(stat="identity")+labs(x="")+theme_bw()+
  theme(axis.text.x=element_text(angle=60,vjust=1,hjust=1))
p2
6857799-fe205247bd0c33c4.png
Rplot08.png
  • 3 散点图
p3<-ggplot(df_bar,aes(x=wt,y=mpg,color=factor(cyl),shape=factor(cyl)))+
  geom_point()+theme_bw()+
  theme(legend.title = element_blank(),
        legend.key.size = unit(2,"cm"),
        legend.background = element_blank(),
        legend.position=c(0.8,0.7))
p3
6857799-46a1c24b59f945ce.png
Rplot09.png

怎么把图例的背景去掉呢???

第三步合并
library(ggpubr)
ggarrange(p1,p2,p3,ncol=2,nrow=2,labels=c("A","B","C"))
6857799-a2fcb34b5b1a7151.png
Rplot10.png
ggarrange(p2,ggarrange(p1,p3,ncol=2,labels=c("B","C")),nrow=2,labels="A")
6857799-60678be5cdd7afbb.png
Rplot11.png

https://blog.csdn.net/superbfly/article/details/45971791
http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/
https://ggplot2.tidyverse.org/reference/guide_legend.html
https://www.zhihu.com/question/56389259
https://cran.r-project.org/web/packages/gridExtra/vignettes/arrangeGrob.html

猜你喜欢

转载自blog.csdn.net/weixin_33806914/article/details/87481670