前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >R语言之可视化①④一页多图(1)目录

R语言之可视化①④一页多图(1)目录

作者头像
用户1359560
发布2018-12-14 14:37:46
8340
发布2018-12-14 14:37:46
举报
文章被收录于专栏:生信小驿站生信小驿站

这里要分享一页多图其实就是指,在做了很多图的情况下,如何将诸多图表合理的布局在一张大的版面上,而不是一幅一幅的导出最后在其他软件中手动拼凑。这个技能在制作多图仪表盘场景下,将会特别有用。还需要强调下这里所指的一页多图与我们之前介绍过的分面可是大有不同,分面其实是一幅图表中,将分类变量所构成的分类图表分图呈现,但是本质上所有分面内的单个图表共享标题、图例、坐标轴刻度(虽然可以手动定义)。也就是说分面的图表类型与诸多元素都是一样的,但是分面解决不了不同图表的排版布局问题:比如单独绘制而成的一幅散点图、柱形图和一幅饼图,分面将无能为力。

R语言中可以实现多图同页布局的函数有很多,这里只跟介绍一种自定义一页多图函数:

代码语言:javascript
复制
library(ggplot2)

# This example uses the ChickWeight dataset, which comes with ggplot2
# First plot
p1 <- ggplot(ChickWeight, aes(x=Time, y=weight, colour=Diet, group=Chick)) +
  geom_line() +
  ggtitle("Growth curve for individual chicks")

# Second plot
p2 <- ggplot(ChickWeight, aes(x=Time, y=weight, colour=Diet)) +
  geom_point(alpha=.3) +
  geom_smooth(alpha=.2, size=1) +
  ggtitle("Fitted growth curve per diet")

# Third plot
p3 <- ggplot(subset(ChickWeight, Time==21), aes(x=weight, colour=Diet)) +
  geom_density() +
  ggtitle("Final weight, by diet")

# Fourth plot
p4 <- ggplot(subset(ChickWeight, Time==21), aes(x=weight, fill=Diet)) +
  geom_histogram(colour="black", binwidth=50) +
  facet_grid(Diet ~ .) +
  ggtitle("Final weight, by diet") +
  theme(legend.position="none")        # No legend (redundant in this graph)    

首先分别定义四个图片,然后定义多图函数。

代码语言:javascript
复制
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))
    }
  }
}

multiplot(p1, p2, p3, p4, cols=2)
#> `geom_smooth()` using method = 'loess'
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.11.20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档