R可视化:多个图形合并在同一面板

多个图形合并在同一面板

文献主图一般是由多个子图构成,我们通常会使用Adobe illustrator软件拼接子图,但现在R提供了多种拼接子图方式。利用程序拼接子图在一个画板会避免耗时耗力的AI修图,而且更体现了生信分析的可重复性特性。更多知识分享请到 https://zouhua.top/

使用grid包

  • 简单的设置layout函数

library(grid)
pushViewport(viewport(layout = grid.layout(2,4)))
vplayout <- function(x, y){
  viewport(layout.pos.row = x, layout.pos.col = y)
}
print(g1, vp = vplayout(1, 1))
print(g2, vp = vplayout(1, 2))
print(g3, vp = vplayout(1, 3))
print(g4, vp = vplayout(1, 4))
  • 复杂版本的layout函数

# Multiple plot function
#
# ggplot objects can be passed in ..., or to plotlist (as a list of ggplot objects)
# - cols:   Number of columns in layout
# - layout: A matrix specifying the layout. If present, 'cols' is ignored.
#
# If the layout is something like matrix(c(1,2,3,3), nrow=2, byrow=TRUE),
# then plot 1 will go in the upper left, 2 will go in the upper right, and
# 3 will go all the way across the bottom.
#
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))
    }
  }
}

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(p1, p2, p3, p4, cols=2)
R可视化:多个图形合并在同一面板_第1张图片

使用 gridExtra包

library(gridExtra)
library(grid)

grid.arrange(p1, p2, p3, p4, newpage = TURE)

do.call(gird.arrange, plotlist)
R可视化:多个图形合并在同一面板_第2张图片

使用cowplot包,可以给每张图打标签

d <- data.frame(matrix(rnorm(100), ncol=10))
colnames(d) <- paste0('t', 1:10)
rownames(d) <- paste0('g', 1:10)
library(pheatmap)
pheatmap(d) -> x

p  <- ggplot(d, aes(t1, t2)) + geom_point(size=5)
library(cowplot)
plot_grid(x$gtable, p, labels=c('A', 'B'))
R可视化:多个图形合并在同一面板_第3张图片

使用patchwork包

library(ggplot2)
library(patchwork)

d1 <- runif(500)
d2 <- rep(c("Treatment","Control"),each=250)
d3 <- rbeta(500,shape1=100,shape2=3)
d4 <- d3 + rnorm(500,mean=0,sd=0.1)
plotData <- data.frame(d1,d2,d3,d4)
str(plotData)

p1 <- ggplot(data=plotData) + geom_point(aes(x=d3, y=d4))
p2 <- ggplot(data=plotData) + geom_boxplot(aes(x=d2,y=d1,fill=d2))+
theme(legend.position="none")
p3 <- ggplot(data=plotData) +
  geom_histogram(aes(x=d1, color=I("black"),fill=I("orchid")))
p4 <- ggplot(data=plotData) +
  geom_histogram(aes(x=d3, color=I("black"),fill=I("goldenrod")))

(p1 | p2)/(p3 | p4)
R可视化:多个图形合并在同一面板_第4张图片

参考

  1. cookbook_grid
  2. gridExtra
  3. cowplot
  4. patchwork

参考文章如引起任何侵权问题,可以与我联系,谢谢。

你可能感兴趣的:(R可视化:多个图形合并在同一面板)