【问题标题】:Plot undetermined number of plots using ggplot2使用 ggplot2 绘制未确定数量的图
【发布时间】:2018-01-29 12:31:18
【问题描述】:

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

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

【问题讨论】:

    标签: r plot ggplot2 pca


    【解决方案1】:

    这是一个开始,获取用户输入 (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])
    

    【讨论】:

    • 啊,是的,这就是我想知道的,cowplot 实际上可以读取 ggplot 对象的列表,这真是太棒了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 2019-01-15
    相关资源
    最近更新 更多