经常需要根据的需求把多张图放在一页,这是facet_wrap和facet_grid并不管用,基本函数mpar在ggplot函数中并不能实现。
以下函数可以将多个图组合在一页
# 第一种
multiplot<-function(..., plotlist=NULL, file, cols=1, layout=NULL){
library(grid)
# Make a list from the ... arguments and plotlist
plots<-c(list(...), plotlist)
numPlots=length(plots)
# If layout is NULL, then use 'cols' to determine layout
if(is.null(layout)){
# Make the panel
# ncol: Number of columns of plots
# nrow: Number of rows needed, calculated from
# of cols
layout<-matrix(seq(1, cols*ceiling(numPlots/cols)),
ncol=cols, nrow=ceiling(numPlots/cols))
}
if(numPlots==1){
print(plots[[1]])
} else {
# Set up the page
grid.newpage()
pushViewport(viewport(layout=grid.layout(nrow(layout), ncol(layout))))
# Make each plot, in the correct location
for(i in 1:numPlots){
# Get the i,j matrix positions of the regions that contain this subplot
matchidx<-as.data.frame(which(layout==i, arr.ind=TRUE))
print(plots[[i]], vp=viewport(layout.pos.row=matchidx$row,
layout.pos.col=matchidx$col))
}
}
}
# 第二种方法
grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 2)))
vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)
print(a, vp = vplayout(1, 1:2))
p <- ggplot(data = diamonds, aes(x = carat, y = price)) + xlim(1, 3) + theme(legend.position = 'none')
a <- p + geom_point() + geom_density2d() + labs(title = '等高线估计')
b <- p + stat_density2d(geom = 'point', aes(size = ..density..), contour = F) + scale_size_area() +
labs(title = 'stat_density二维密度估计')
c <- p + stat_density2d(geom = 'tile', aes(fill = ..density..), contour = F)
multiplot(a, b, c, cols = 2) # 按列