# R: Plotting 4x4 plot with for -loop and png, why getting 1x1 plot instead of 4x4?

I can get the 4x4 plot working when I try it on command line but not with for -loop and png element in the code below. I am frustrated what the heck the problem is, I have tried to understand this now hours and cannot advance.

Just $R CMD Sweave paper.Rnw,$ pdflatex paper.tex and $evince paper.pdf after you copy the code below to paper.Rnw -file -- and you will get a 1x1 plot instead of 4x4 plot. Why? $ mkdir Pictures
$mkdir Data$ cd Data
$wget https://noppa.aalto.fi/noppa/kurssi/mat-2.3128/harjoitustyot/Mat-2_3128_data_2.xls$ cd ..
\$ cat paper.Rnw

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{amsfonts}
\usepackage{amsmath}
\usepackage{graphicx}

\begin{document}

<<echo=FALSE>>=
library(gdata)

for(i in 1:ncol(f))
{
png(paste('./Pictures/CO',i,'.png',sep =''))
par(mfrow=c(2,2))
plot(pacf(na.omit(f[,i])), main=paste('Pacf', i))
plot(acf(na.omit(f[,i])), main=paste('Acf', i))
plot(na.omit(f[,i]), main=paste('Data', i), type='l')
}
@

\subsection{Time-serie C1}
\includegraphics{./Pictures/CO1.png}
\subsection{Time-serie C2}
\includegraphics{./Pictures/CO2.png}
\subsection{Time-serie C3}
\includegraphics{./Pictures/CO3.png}
\subsection{Time-serie C4}
\includegraphics{./Pictures/CO4.png}
\subsection{Time-serie C5}
\includegraphics{./Pictures/CO5.png}

\end{document}


The functions acf and pacf have an argument plot which defaults to TRUE. Thus, the plot statement is not required (otherwise you get two plots for acf and two plots for pacf). Note, I also added a dev.off() statement.

This should work:

for(i in 1:ncol(f))
{
png(paste('./Pictures/CO',i,'.png',sep =''))
par(mfrow=c(2,2))
pacf(na.omit(f[,i]), main=paste('Pacf', i))
acf(na.omit(f[,i]), main=paste('Acf', i))
plot(na.omit(f[,i]), main=paste('Data', i), type='l')
dev.off()
}
@