一页多图

 经常需要根据的需求把多张图放在一页,这是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) # 按列



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值