ggplot in a loop

If you are using a for loop to output multiple plots, ggplot doesn't work.

I was trying to export multiple plots to PDF using ggplot2. However, the output file shows nothing. Thanks to the stackoverflow tip: to put print before ggplot

library(ggplot2)
cpm_norm <- read.delim("meanCPM.txt", sep=" ", row.names="id")
GI<-scan(file="id2plot", what=character());
pdf("exp.pdf")
i<-1;
for (i in 1:length(GI)) {
rown<-GI[i];
expdata<-
  data.frame(
    male=as.numeric(cpm_norm[rown, c("Testis", "Egg", "Mir", "Spo", "mCerc", "mSom1", "mSom2", "mSom3", "sM", "bM")]),
    female=as.numeric(cpm_norm[rown, c("Ovary", "Egg", "Mir", "Spo", "fCerc", "fSom1", "fSom2", "fSom3", "sF", "bF")]),
    stage=c("Gonad", "Egg", "Mira", "Sporo", "Cerc", "Som#1", "Som#2", "Som#3", "Adult_unpaired", "Adult_paired")
)

print(ggplot(expdata, aes(stage)) + geom_line(aes(y=male,group=1), colour="blue") + geom_point(aes(y=male, group=1), colour="blue") + geom_line(aes(y=female, group=1), colour="red") + geom_point(aes(y=female, group=1), colour="red")+ggtitle(rown)+labs(y="Counts per Million", x="Life stage")+scale_x_discrete(limits= expdata$stage)+theme(axis.text.x = element_text(angle = 45, hjust = 1)))
}
dev.off()
Z. Lu avatar
Z. Lu
Computer biologist, amature photographer, vintage fan and web lover.
comments powered by Disqus