plot inside a for loop

122 views
Skip to first unread message

Gary Churchill

unread,
Mar 26, 2012, 5:13:06 PM3/26/12
to ggplot2
I may be missing something basic here, but why does my plot work one
at a time but not when I put it in a loop?

one at a time:
pdf("CumulativeByStrainGenSex.pdf", width=9.5, height=7, onefile=
TRUE)
qplot(Pos, cM, data=subset(G2Map.bySexStrainGen,Chr==1), geom="line",
group=Sex:Gen, lty=Gen,
color=Sex,main=paste("Chromosome", as.character(1), sep=" ")) +
aes(color=Sex) + scale_colour_manual(value=color.sex) +
facet_wrap(~Strain, ncol=2)
....repeat 20 times
dev.off()

in a loop:
pdf("CumulativeByStrainGenSex.pdf", width=9.5, height=7, onefile=
TRUE)
for(i in 1:20){
qplot(Pos, cM, data=subset(G2Map.bySexStrainGen,Chr==i), geom="line",
group=Sex:Gen, lty=Gen,
color=Sex,main=paste("Chromosome", as.character(i), sep=" ")) +
aes(color=Sex) + scale_colour_manual(value=color.sex) +
facet_wrap(~Strain, ncol=2)
}
dev.off()

Thanks for any help with this...
Gary

R. Michael Weylandt <michael.weylandt@gmail.com>

unread,
Mar 26, 2012, 8:19:04 PM3/26/12
to Gary Churchill, ggplot2
You need to wrap the last line that constructs your graph (which I think is the whole loop body for you) in print() to trigger the actual plotting. When you do this interactively the REPL automatically prints, but that's turned off inside the loop mechanism.

Canonical answer: see R FAQ 7.31

Hope that helps,
Michael

> --
> You received this message because you are subscribed to the ggplot2 mailing list.
> Please provide a reproducible example: http://gist.github.com/270442
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2

R. Michael Weylandt

unread,
Mar 26, 2012, 9:25:34 PM3/26/12
to Gary Churchill, ggplot2
Pointed out to me by private message that the canonical answer is FAQ
7.22, not 7.31 -- sorry for any confusion that might have caused.

Best,
Michael

Stuart Luppescu

unread,
Mar 27, 2012, 10:46:02 AM3/27/12
to ggp...@googlegroups.com
On Mon, 2012-03-26 at 14:13 -0700, Gary Churchill wrote:
> I may be missing something basic here, but why does my plot work one
> at a time but not when I put it in a loop?

I have had the same problem, and was told that using ggsave() instead of
pdf() will fix this problem.
--
Stuart Luppescu -=- slu .at. ccsr.uchicago.edu
University of Chicago -=- CCSR
才文と智奈美の父 -=- Kernel 3.2.1-gentoo-r2
Obviously I have not tested on an Alphabc...tuvwxyz
system but it should work there. -- Brian D.
Ripley (after fixing a problem discovered when
compiling R 2.0.0 on Linux Alpha)
R-devel (October 2004)




Reply all
Reply to author
Forward
0 new messages