Mikkel Astrup
Mikkel Astrup

Reputation: 415

Saving multiply pdf plots r

I have made a loop for making multiply plots, however i have no way of saving them, my code looks like this:

#----------------------------------------------------------------------------------------#
# RING data: Mikkel
#----------------------------------------------------------------------------------------#
# Set working directory
setwd()

#### Read data & Converting factors ####
dat <- read.table("Complete RING.txt", header =TRUE)  
str(dat)
dat$Vial <- as.factor(dat$Vial)
dat$Line <- as.factor(dat$Line)
dat$Fly <- as.factor(dat$Fly)  
dat$Temp <- as.factor(dat$Temp)
str(dat)

datSUM <- summaryBy(X0.5_sec+X1_sec+X1.5_sec+X2_sec+X2.5_sec+X3_sec~Vial_nr+Concentration+Sex+Line+Vial+Temp,data=dat, FUN=sum)
fl<-levels(datSUM$Line)

colors = c("#e41a1c", "#377eb8", "#4daf4a", "#984ea3")

meltet <- melt(datSUM, id=c("Concentration","Sex","Line","Vial", "Temp", "Vial_nr"))

levels(meltet$variable) <- c('0,5 sec', '1 sec', '1,5 sec', '2 sec', '2,5 sec', '3 sec')

meltet20 <- subset(meltet, Line=="20")
meltet20$variable <- as.factor(meltet20$variable)

AllConcentrations <- levels(meltet20$Concentration)

for (i in AllConcentrations) {
  meltet.i <- meltet20[meltet20$Concentration ==i,]
  quartz()
  print(dotplot(value~variable|Temp, group=Sex, data = meltet.i ,xlab="Time", ylab="Total height pr vial [mm above buttom]", main=paste('Line 20 concentration ', meltet.i$Concentration[1]),
                key = list(points = list(col = colors[1:2], pch = c(1, 2)),
                           text = list(c("Female", "Male")),
                           space = "top"), col = colors, pch =c(1, 2))) }

I have tried with the quartz.save function, but that just overwrites the files. Im using a mac if that makes any difference.

Upvotes: 0

Views: 199

Answers (1)

mfidino
mfidino

Reputation: 3055

When I want to save multiple plots in a loop I tend to do something like...

for(i in AllConcentrations){

meltet.i <- meltet20[meltet20$Concentration ==i,]

pdf(paste("my_filename", i, ".pdf", sep = ""))
  dotplot(value~variable|Temp, group=Sex, data = meltet.i ,xlab="Time", ylab="Total height pr vial [mm above buttom]", main=paste('Line 20 concentration ', meltet.i$Concentration[1]),
            key = list(points = list(col = colors[1:2], pch = c(1, 2)),
                       text = list(c("Female", "Male")),
                       space = "top"), col = colors, pch =c(1, 2))
dev.off()
}

This will create a pdf file for every level in AllConcentrations and save it in your working directory. It will paste together my_filename, the number of the iteration i, and then .pdf together to make each file unique. Of course, you will want to adjust height and width in the pdf function.

Upvotes: 2

Related Questions