Sebastian Zeki
Sebastian Zeki

Reputation: 6874

How to loop through and produce plots on the same page

I have some genetic data I am trying to plot out on a per chromosome basis. The code is as follows:

plot(df[which(df[,1] == "chr7"),2],p_seq[which(df[,1] == "chr7")],type="l",lty=4,xlab="Locus",ylab="Median ZScore")

The dataframe (called df) has all the chromosomes in its first column labelled chr1, chr2 etc to chr22 and then chrX and chrY.

I would like to do the above plot for all the chr in column 1 and have them all on the same page. I would try and loop through chr and a number but X chrX and Y ruin this. Can anyone help?

Upvotes: 0

Views: 834

Answers (1)

eipi10
eipi10

Reputation: 93851

Here are two ways to get multiple plots at once. I've used the mtcars data set, which is built into R:

# PDF file with a separate page for each plot
pdf("plots.pdf", 5,5)

# Make a separate plot of mpg vs. weight for each value of cyl
for (i in unique(mtcars$cyl)) {
  plot(mtcars$wt[mtcars$cyl==i], mtcars$mpg[mtcars$cyl==i],
       xlab=paste0(i," Cylinders"), ylab="mpg")
}
dev.off()

# PDF file with all plots on one page
pdf("plots2.pdf", 5,12)

# Put 3 plots in one column on a single page
par(mfrow=c(3,1))

# Make a separate plot of mpg vs. weight for each value of cyl
for (i in unique(mtcars$cyl)) {
  plot(mtcars$wt[mtcars$cyl==i], mtcars$mpg[mtcars$cyl==i],
       xlab=paste0(i," Cylinders"), ylab="mpg")
}
dev.off()

Upvotes: 4

Related Questions