首页 > 解决方案 > 我想使用一个for循环来生成几个图,使用ggplot2,每个都有单独的hlines

问题描述

我使用基本绘图函数和 for 循环生成了一些图表 - 它为我提供了所需的输出。但是,这些图看起来很可怕 - 所以我尝试使用 ggplot2,但 for 循环无法生成与基本图相同的图

for(j in d1_split$Machine){
  plot(d1$Num[which(d1$Machine==j)], d1$Cq[which(d1$Machine==j)], 
       xlab = j, 
       ylim = c(d1_split$Lower_1[which(d1_split$Machine==j)]-0.25, 
                d1_split$Upper_1[which(d1_split$Machine==j)]+0.25), 
       type = "b", col = "black", pch = 16)
  abline(h = d1_split$Avg[which(d1_split$Machine==j)], col = "red")
  abline(h = d1_split$Upper_1[which(d1_split$Machine==j)], col = "red")
  abline(h = d1_split$Lower_1[which(d1_split$Machine==j)], col = "red")
}
# This semi-works - gives multiple plots with all machines, each with different mean/sd lines
for(i in d1_split$Machine){
  print(ggplot(d1,
         aes(x = Num, y = Cq, col = Machine)) +
    geom_point(size=2) +
    geom_line() +
    xlab(NULL) +
    ylab("Cq value") +
    facet_wrap(~ Machine, nrow = 2, ncol = 4) +
    geom_hline(yintercept=d1_split$Avg[which(d1_split$Machine==i)], 
               linetype="dashed", color="red") +
    geom_hline(yintercept=d1_split$Upper_1[which(d1_split$Machine==i)], 
               linetype="dashed", color="red") +
    geom_hline(yintercept=d1_split$Lower_1[which(d1_split$Machine==i)], 
               linetype="dashed", color="red") +
    theme(axis.text.x = element_text(colour = "black", angle = 45, vjust = 0.5), 
          axis.title=element_text(size=16, colour = "black"), 
          axis.text=element_text(size=14, colour = "black"),
          axis.line = element_line(colour = "black"),
          panel.background = element_blank(),
          legend.text = element_text(size=12),
          legend.title = element_text(size=14), 
          legend.box.background = element_rect(colour = "black")))
}```

I'd like for the ggplot2 for-loop to produce graphs each with different hlines for each facet wrap - but they are always the same - Can anyone spot where I may be going wrong??

标签: rggplot2

解决方案


推荐阅读