我有一個很長的結果資料框。有 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")
uj5u.com熱心網友回復:
我沒有使用您的示例,而是在下面提供了一個使用合成資料集的更簡單示例。多頁pdf的關鍵是onefile = TRUE在打開pdf設備時使用引數:
# 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()
uj5u.com熱心網友回復:
我最終通過從一個大 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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315495.html
