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

目录

R语言之可视化①误差棒

R语言之可视化②点图

R语言之可视化③点图续

R语言之可视化④点韦恩图upsetR

R语言之可视化⑤R图形系统

R语言之可视化⑥R图形系统续

R语言之可视化⑦easyGgplot2散点图

R语言之可视化⑧easyGgplot2散点图续

R语言之可视化⑨火山图

R语言之可视化⑩坐标系统

R语言之可视化①①热图绘制heatmap

R语言之可视化①②热图绘制2

R语言之可视化①③散点图+拟合曲线

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

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

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

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)    

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

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'