通过构建multiplot函数,能够很容易地做到一页多图,该函数的具体定义附在末尾,如果它并不能完全满足你的需求,可以复制它并在它的基础上进行修改。
首先,构建一系列图像,但不直接去渲染它们,图像的具体细节并不重要,我们只需要将这些图像对象全部存储为变量。
- library(ggplot2)
-
- # 下面的例子用到了ggplot2包中自带的示例数据集ChickWeight
- # 首先创建图像,第一幅图像——折线图
- p1 <- ggplot(ChickWeight, aes(x=Time, y=weight, colour=Diet, group=Chick)) +
- geom_line() +
- ggtitle("Growth curve for individual chicks")
-
- # 第二幅图像——密度分布图
- 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")
-
- # 第三幅图像——带拟合线的散点图
- p3 <- ggplot(subset(ChickWeight, Time==21), aes(x=weight, colour=Diet)) +
- geom_density() +
- ggtitle("Final weight, by diet")
-
- # 第四幅图像——分面直方图
- 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") # 无图例(在这幅图中,图例显得太冗余了)
接下来,我们可以用multiplot函数对创建的图像进行渲染,将它们展示为两行。
- multiplot(p1, p2, p3, p4, cols=2)
- #> 载入需要grid包
- #> geom_smooth: method="auto" and size of largest group is <1000, so using loess. Use 'method = x' to change the smoothing method.
下面是multiplot函数的具体定义,你可以把任意数量的图像名作为其参数,或者构建一个图像列表作为函数中的plotlist。
- # 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))
- }
- }
- }
以上内容转自 数析学院 ,还有更多免费的资源,感兴趣的同学可以直接访问查看