2014-11-25 17 views
0

我試圖用多個圖表打印一個pdf。 我正在使用一個循環和ggplot,這也是一個函數。 我在'註釋'情節時遇到了麻煩。 我想註釋該狀況的中位數和總體中位數。 我正在使用水平線(geom_hline)和註釋('文本')來標記這些線條。在循環內註釋ggplots geom_hline是錯誤的

問題是單詞被正確放置(即註釋(「文本」,x = 1,y = Cmedian)似乎正常工作,但水平線被繪製在錯誤的位置(即。 geom_hline(aes(yintercept = Cmedian)不起作用,它總是將Cmedian行放在30處,並將allmedian行放在22.

我有時在循環或函數中有ggplot的'奇怪'行爲,想知道如何避免這種情況。

任何幫助表示讚賞。 謝謝

suspect_conds<-c(head(suspect_SumPheno[rev(order(suspect_SumPheno$zscore)),],n=20)$condition,tail(suspect_SumPheno[rev(order(suspect_SumPheno$zscore)),],n=20)$condition) 

pdf(paste(out_dir,paste(set,org,"bar.SuspectConditionssumPhenoPerPlate.pdf",sep="."),sep="")) 
for (i in 1:length(suspect_conds)){ 
    cond<-suspect_conds[i] 
    cond_subset<-PhenoSumPerPlatPerCond[PhenoSumPerPlatPerCond$condition==cond,] 

    Cmedian<-median(cond_subset$sum_pheno) 
    allmedian<-median(PhenoSumPerPlatPerCond$sum_pheno) 
    plateMedians<-aggregate(sum_pheno~plate,data=PhenoSumPerPlatPerCond,median) 

    p<-ggplot(cond_subset, aes(x=plate, y=sum_pheno, fill=plate)) + geom_bar(stat="identity") + 
     labs(title=paste("total phenotypes per plate in",cond,sep=" ")) + 
     geom_hline(aes(yintercept=Cmedian), colour="black")+ geom_hline(aes(yintercept=allmedian), colour="black",linetype="dashed")+ 
     annotate("text", x = 1, y = Cmedian, label = "median number of phenotypes per plate in this condition",hjust=0,vjust=0)+ 
     annotate("text", x = 1, y = allmedian, label = "median number of phenotypes per plate",hjust=0,vjust=0)+ 
     geom_point(data=plateMedians,aes(x=plate,y=sum_pheno),colour="black",size=4)+ 
     theme_bw() 

print(p,file=paste(out_dir,paste(set,org,cond,"bar.sumPhenoPerPlate.pdf",sep="."),sep="")) 
} 
dev.off() 

回答