以下内容来自教程
R语言中多张图画到同一个页面上常用的函数为par()和layout()
par()函数详解
layout()函数的简单使用
但是这两个函数不适用于ggplot2;ggplot2作图如果希望把多张图放到同一个页面上基本的解决办法是使用(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
df_box$dose
ggplot(data=df_box,aes(x=dose,y=len,group=dose))+
geom_boxplot()+theme_bw()
p1
Rplot02.png
2 柱形图
柱形图安装从小到大的顺序往后画,印象里是可以用reorder()函数实现的,但是想不起来怎么用了,刚刚找到了一个教程,reorder是放在aes()中x的位置,reorder第一个参数是排序的因子变量,第二个是数值变量R中排序函数总结:sort,order,rank,arrange,reorder
df_bar
df_bar$name
df_bar$name
p2
geom_bar(stat="identity")+labs(x="")+theme_bw()+
theme(axis.text.x=element_text(angle=60,vjust=1,hjust=1))
p2
Rplot08.png
3 散点图
p3
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
Rplot09.png
怎么把图例的背景去掉呢???
第三步合并
library(ggpubr)
ggarrange(p1,p2,p3,ncol=2,nrow=2,labels=c("A","B","C"))
Rplot10.png
ggarrange(p2,ggarrange(p1,p3,ncol=2,labels=c("B","C")),nrow=2,labels="A")
Rplot11.png