多个ggplot2绘图的布局,当一些居中时

时间:2018-01-04 16:04:28

标签: r ggplot2

我试图在R中为我的panelplot找到一个不错的布局。我有五个子图,想要一个有2列3行的矩阵。第一个子图应该在第1行居中,其余四个子图进入第二和第三行。我希望每个子图都具有相同的大小。

library(mgcv)
library(ggplot2)
library(grid)
theme_set(theme_bw())

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, group=Chick)) +
geom_line() +
ggtitle("Growth curve for individual chicks")

p3 <- ggplot(ChickWeight, aes(x=Time, y=weight, colour=Diet, group=Chick)) +
geom_line() +
ggtitle("Growth curve for individual chicks")

p5 <- ggplot(ChickWeight, aes(x=Time, y=weight, colour=Diet, group=Chick)) +
geom_line() +
ggtitle("Growth curve for individual chicks")

p6 <- ggplot(ChickWeight, aes(x=Time, y=weight, colour=Diet, group=Chick)) +
geom_line() +
ggtitle("Growth curve for individual chicks")

p4 <- plot.new()

# Define multiplot function
multiplot <- function(..., plotlist = NULL, file, cols = 1, layout = NULL) {
  require(grid)

  plots <- c(list(...), plotlist)

  numPlots = length(plots)

  if (is.null(layout)) {
    layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
                ncol = cols, nrow = ceiling(numPlots/cols))
  }

  if (numPlots == 1) {
    print(plots[[1]])

  } else {
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(nrow(layout),  ncol(layout))))

    for (i in 1:numPlots) {
      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))
    }
  }
}

pdf("test.pdf")
# # Plot multiplot
multiplot(p1, p2, p3, p4, p5, p6, cols = 2)

为简单起见,我没有打印完整的绘图命令。

2 个答案:

答案 0 :(得分:1)

安排多个绘图的一种方法是使用multipanelfigure包。

创建示例图:

library(ggplot2)
plots <- list()
for(i in 1:5) {
    plots[[i]] <- ggplot() + ggtitle(paste("My plot:", i))
}

为图表创建面板:

library(multipanelfigure)
figure <- multi_panel_figure(columns = 4, rows = 3, panel_label_type = "none")

我们使用具有指定列数和行数的函数multi_panel_figure()。您只需要2列,但是如果您想要将一个图集居中,我们将使用4列(中心将是第2列和第3列)。

在面板上添加图表:

figure %<>%
    fill_panel(plots[[1]], column = 2:3, row = 1) %<>%
    fill_panel(plots[[2]], column = 1:2, row = 2) %<>%
    fill_panel(plots[[3]], column = 3:4, row = 2) %<>%
    fill_panel(plots[[4]], column = 1:2, row = 3) %<>%
    fill_panel(plots[[5]], column = 3:4, row = 3)

结果:

enter image description here

答案 1 :(得分:0)

您的解决方案对我不起作用,因为我无法安装multipanelfigure,但这有效(如果有人有类似的问题)。这与PoGibas的做法基本相同,但没有多面包装:

    #pragma once

#include <vector>

typedef std::vector<uint8_t> CommonType;

std::ostream& operator << (std::ostream& os, const CommonType& bb)
{
        for (auto& el : bb)
        {
            os << el;
        }
        return os;
}