这里我们使用grid对ggplot的画图对象进行布局
# 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.
# e=0.15, # extra height needed for last plot (vertical layout),
# or extra width for first plot (horizontal layout)
multiplot <- function(..., plotlist=null, file, cols=1,
layout=null, horizontal=false, e=0.15) {
require(grid)
# make a list from the ... arguments and plotlist
plots = c(list(...), plotlist)
numplots = length(plots)
#message(paste0('>>>>>>>info: num plots 2 = ', numplots), '\n')
# 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 heights/widths of plots
# extra height needed for last plot (vertical layout),
# or extra width for first plot (horizontal layout)
hei = rep(1, numplots)
# bottom plot is taller
hei[numplots] = hei[numplots]*(1 e)
wid = rep(1, numplots)
# first left plot is wider
wid[1] = wid[1]*(1 e)
# set up the page
grid.newpage()
if(horizontal){
pushviewport(viewport(layout = grid.layout(nrow(layout),
ncol(layout), widths=wid)))
}else{
pushviewport(viewport(layout = grid.layout(nrow(layout),
ncol(layout), heights=hei)))
}
# make each plot, in the correct location
for (i in 1:numplots) {
# get i,j matrix positions of the regions containing 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)
p1 <- ggplot(iris, aes(x = sepal.length)) geom_histogram() theme_bw()
p2 <- ggplot(iris, aes(x = sepal.length, y = petal.width)) geom_point() theme_bw()
# 直接使用ggplot对象画图
multiplot(p1,p2)
# 将ggplot对象放入列表中,再用列表画图, 并设置两列的排列方式
plot_lst <- list()
plot_lst[[1]] <- p1
plot_lst[[2]] <- p2
multiplot(plotlist = plot_lst, cols = 2)
参考资料
clonevol: clonal ordering and visualization in cancer
sequencing文献里面cloneevol包里面boxplot.r函数
原文链接:http://www.cnblogs.com/ywliao/p/12419025.html