I am trying to print a pdf with multiple plots. I am using a loop and ggplot, also this is inside a function. I am having trouble with 'annotating' the plot. I want to annotate the median for that condition, and the overall median. I am using a horizontal line (geom_hline) and annotate ('text') to label these lines.
The problem is that the words are being placed correctly (ie. annotate("text", x = 1, y = Cmedian) seems to work correctly, but the horizontal line is being drawn at the wrong location (ie. geom_hline(aes(yintercept=Cmedian) doesn't work,. It is always placing the Cmedian line at 30 and the allmedian line at 22.
I sometimes have 'strange' behaviours with ggplot inside a loop or a function and am wondering how to avoid this.
Any help is appreciated. Thank you,
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()