在一页上循环绘制多个图形

时间:2020-06-05 08:13:47

标签: r loops ggplot2 graph cowplot

我有一个循环,可从大型数据集中为每列绘制两个图形。现在,在该循环中,我将图形P1和P2都绘制在一页上,然后移至下一页,将在下一页绘制P​​1 P2列。

但是,在进入下一页之前,我实际上想在一页上绘制多列(P1和P2):第1列P1和P2,第2列P1和P2,然后移至下一页。

请在下面找到我现在使用的代码的简化。

制作数据集

library(ggplot2)
library(cowplot)

    group <- c("Control","PAD","Control","PAD","PAD", "Control","PAD","Control","PAD","PAD", "Control","PAD","Control","PAD","PAD")
b <- round(runif(15, 1, 7)) 
c <- round(runif(15, 1, 3)) 
d <- round(runif(15, 3, 8)) 
e <- round(runif(15, 1, 5))
tissue <- c("Homogenate", "Plasma" , "Homogenate" , "Plasma" , "Homogenate", "Plasma" , "Homogenate" , "Plasma", "Homogenate", "Plasma" , "Homogenate" , "Plasma", "Homogenate", "Plasma" , "Homogenate")


df <- data.frame(group, b,c,d, e, tissue)
df

rm(group, b, c, d, e, tissue)

遍历数据集,同时每列制作两个图形并将其存储为PDF

    pdf("------------.pdf", width = 15)
for (i in names(df)[2:5]){

p1 <- ggplot(df, aes_string("tissue",i)) + 
  geom_boxplot(show.legend = F)



p2 <- ggplot(df, aes_string("tissue",i)) + 
  geom_boxplot(show.legend = F)


p_all <- plot_grid(p1,p2)



# create a title vector for i
title <- ggdraw() +
  draw_label(i, 
             fontface = "bold",
             x = 0,
             hjust = 0,
             size = 25) +
  theme(
    # add margin on the left of the drawing canvas
    plot.margin = margin(0,0,0,7,))




p_all <- plot_grid(title, p_all, ncol=1, nrow=3, rel_heights = c(0.1,1))
print(p_all)
} 
dev.off()

0 个答案:

没有答案