在R中实现一页多图,如果用R基础函数绘图,相对比较容易,如果用ggplot2绘图,实现起来相对比较麻烦,我给大家介绍下两种情况下的实现方法:
1. R基础绘图一页多图之par函数
R基础函数绘图,可以通过par函数的mfcol或者mfrow参数设置,mfcol按照列排列,mfrow按照行排列;
比如par(mfcol = c(2, 2)),表示2行2列,共4幅图,并且按照列排列;
以iris数据集作为示例:
#保存图片
pdf('test.pdf')
#通过par函数的mfcol参数设置绘图排版,mai参数设置每幅图的边距
par(mfcol = c(2,2), mai=c(0.7,0.7,0.3,0.2))
#绘制第一幅图
plot(iris$Sepal.Length, iris$Sepal.Width, main = 'This is first plot')
#绘制第二幅图
plot(iris$Sepal.Length, iris$Sepal.Width,xlab = 'Sepal.Length',ylab='Sepal.Width',main='This is second plot')
#绘制第三幅图
plot(iris$Sepal.Length, iris$Sepal.Width,xlab = 'Sepal.Length',ylab='Sepal.Width',main='This is third plot',pch=16,col = iris$Species)
#绘制第四幅图
plot(iris$Sepal.Length, iris$Sepal.Width,xlab = 'Sepal.Length',ylab='Sepal.Width',main='This is fourth plot',pch=16,col = iris$Species)
#给第四幅图添加图例
legend('topright',legend=unique(iris$Species),pch=16:19,col=unique(iris$Species))
dev.off()
2. ggplot一页多图绘制之gridExtra
ggplot要想实现一页多图,最简单的办法是,借助于工具包gridExtra(当然也可以用grid实现,不过比较复杂,但是可以控制细节,也可以完成复杂度高的组合图形),在此主要介绍gridExtra的实现方式:
p1 ->
geom_boxplot() +
ggtitle('This is first plot') +
theme(axis.title = element_text(size = 14),
axis.text = element_text(size = 12),
plot.title = element_text(hjust = 0.5))
p2 ->
geom_boxplot() +
theme_bw() +
ggtitle('This is second plot') +
theme(axis.title = element_text(size = 14),
axis.text = element_text(size = 12),
plot.title = element_text(hjust = 0.5))
p3 ->
geom_point() +
ggtitle('This is third plot') +
theme(axis.title = element_text(size = 14),
axis.text = element_text(size = 12),
plot.title = element_text(hjust = 0.5))
p4 ->
geom_point() +
theme_bw() +
ggtitle('This is fourth plot') +
theme(axis.title = element_text(size = 14),
axis.text = element_text(size = 12),
plot.title = element_text(hjust = 0.5))
#保存图片
pdf('test_ggplot.pdf')
#排列图形,ncol,nrow分别设着行列放置几张图
grid.arrange(p1, p2, p3, p4, ncol = 2, nrow = 2)
#关闭图形设备
dev.off()
3. 再来一个子母图绘制工具--viewport
ggplot也可以实现子母图,可以通过viewport实现,viewport是grid绘图体系用于排版的函数(ggplot是基于grid绘图原理设计的):
viewport主要的参数有4个,x和y设置中心位点相对于父图层的位置,width和height设置子图形的大小,如下图所示:
实战
p5 ->
geom_point(size = 2) +
theme_bw() +
ggtitle('This is main plot') +
xlim(4, 10) +
theme(axis.title = element_text(size = 16),
axis.text = element_text(size = 14),
plot.title = element_text(hjust = 0.5),
legend.position = 'none')
p6 ->
geom_boxplot() +
theme_bw() +
ggtitle('This is submain plot') +
theme(axis.title = element_blank(),
axis.text = element_text(size = 8),
plot.title = element_text(hjust = 0.5),
legend.position = 'none')
pdf('test_main.pdf')
subvp ->
p5
print(p6, vp = subvp)
def.off()
/End.