使用 ggplot2 绘制未确定数量的图

Plot undetermined number of plots using ggplot2

我正在尝试使用 ggplot2 绘制主成分分析的内容。我想生成一个 pdf,其中包含用户指定数量的要显示的所有图(因此,如果用户说 3,它将绘制 PC 1 vs 2、1 vs 3 和 2 vs 3)。

我已经研究了 gridextra,但不完全确定当我不知道将选择多少个组件时如何添加多个图。

这是一个开始,获取用户输入 (input_nPC),获取组合然后循环并绘制数据子集:

library(ggplot2)

# example data
myPC <- data.frame(
  pc1 = runif(10),
  pc2 = runif(10),
  pc3 = runif(10),
  pc4 = runif(10))

# user input, e.g.: 3 out of 4 PCs
input_nPC <- 3

# check: must be at least 2 PCs
input_nPC <- max(c(2, input_nPC))

# get combination
combo <- combn(input_nPC, 2)

pdf("myOutput.pdf")

for(i in seq(ncol(combo))){
  d <- myPC[, combo[, i]]
  d_cols <- colnames(d)
  gg <- ggplot(d, aes_string(x = d_cols[1], y = d_cols[2])) +
    geom_point() +
    ggtitle(paste(d_cols, collapse = " vs "))
  print(gg)
}

dev.off()

如果我们需要输出一页 PDF,则使用 cowplot 包:

ggList <-
  apply(combo, 2, function(i){

    d <- myPC[, i]
    d_cols <- colnames(d)
    ggplot(d, aes_string(x = d_cols[1], y = d_cols[2])) +
      geom_point() +
      ggtitle(paste(d_cols, collapse = " vs "))

  })

pdf("myOutput.pdf")
cowplot::plot_grid(plotlist = ggList)
dev.off()

或者我们可以使用 GGally::ggpairs 如下:

library(GGally)

ggpairs(myPC[, 1:input_nPC])