【问题标题】:How to loop/generate many plots using ggplot on the same data frame如何在同一数据帧上使用 ggplot 循环/生成许多图
【发布时间】:2021-12-02 17:35:58
【问题描述】:

我有一个很长的结果数据框。有 148 次曝光和 148 次结果,每一次都相对于另一次进行了回归(148*148 = 21,904 - df 中的行数)。

我想针对 148 个结果绘制每次曝光的结果 - 所以我想要总共 148 个图。下面的代码对一次曝光执行此操作并生成一个图。

**问题:**如何最好地为所有 148 次曝光执行此操作并导出为多页 PDF 和/或单独的 PDF 文件?

# libraries 

library(qs)
library(dplyr)
library(ggplot2)
library(ggrepel)

# make data

set.seed(15)
res_df <- data.frame(exp = randomStrings(N = 148, string_size = 4))
res_df <- data.frame(res_df[rep(seq_len(nrow(res_df)), each = 148), ])
colnames(res_df)[1] <- "exp"
res_df <- mutate(res_df, y = randomStrings(N = 148, string_size = 5),
                 logp = abs(rnorm(n = 148, mean = 5, sd = 6)),
                 r = rnorm(n = 148, mean = 0.5, sd = 0.1))

# subset df for individiual plot

subset <- res_df[1,1]
res_df_a <- subset(res_df, exp == subset)

# PLOT

ggplot(res_df_a, aes(x = r, y = logp, label = y)) +
  geom_point(data = res_df_a[res_df_a$logp < 10,], color = "grey50") +
  geom_text_repel(data = res_df_a[res_df_a$logp > 10,], box.padding = 0.5, max.overlaps = Inf) +
  geom_point(data = res_df_a[res_df_a$logp > 10,], color = "red")+
  xlab("Variance explained (%)") + ylab("-log10(pvalue)") +
  ggtitle("y ~ exp")

【问题讨论】:

    标签: r loops ggplot2


    【解决方案1】:

    我没有使用您的示例,而是在下面提供了一个使用合成数据集的更简单示例。多页pdf的关键是在打开pdf设备时使用参数onefile = TRUE

    # required libraries ------------------------------------------------------
    library(ggplot2)
    
    # make data ---------------------------------------------------------------
    set.seed(1)
    df <- data.frame(x = cumsum(rnorm(10)), y = cumsum(rnorm(10)))
    
    # make sequential plot and send output to pdf device ----------------------
    pdf("plotseq.pdf", width = 5, height = 5, onefile = TRUE)
    for(i in seq(nrow(df))){
      p <- ggplot(df) + aes(x = x, y = y) +
        geom_point(shape = 1) + 
        geom_point(data = df[i,]) + 
        labs(title=paste("i =", i))
      print(p)
    }
    dev.off()
    

    【讨论】:

    • 感谢您的回复。使用我的示例,这种方法将给我 21,904 个不同的图,因为它是按行循环的?我想循环曝光(148 次曝光)。
    【解决方案2】:

    我最终通过从一个大的 df 制作数据帧列表然后绘制每个 df 并保存来设法找出答案。使用上面的代码制作数据然后:

    library(gridExtra)
    # make list of data frames
    
    obs_lists <- split( res_df , f = res_df$exp )
    
    # plot each df within the list and write out to PDFs
    
    p <- lapply(obs_lists, function(d) ggplot(
      data = d, aes(x = r, y = logp)) + geom_point()
    )
    
    # 6 per page
    ggsave("multi.pdf", gridExtra::marrangeGrob(grobs = p, nrow=3, ncol=2, top = NULL))
    
    # 1 per page 
    pdf("single.pdf", onefile = TRUE)
    p
    dev.off()
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      相关资源
      最近更新 更多