title: R_Multiple plots on same figure using a for loop
body: <p>I have 2 data frames, mydf1 and mydf2</p>
  
  <pre><code>&gt; mydf1
    id a  b  c
  1  1 2 10  2
  2  2 3 11  4
  3  3 5 12  6
  4  4 7 13  8
  5  5 8 14 10
  &gt; mydf2
    id  a  b  c
  1  1  4 20  4
  2  2  6 22  8
  3  3 10 24 12
  4  4 14 26 16
  5  5 16 28 20
  </code></pre>
  
  <p>I would like to plot variables a,b &amp; c against id (sample graphs is given below). <strong>I want similar graphs for variables b and c too and I want to do it in a loop and then export it to a local folder.</strong> So, I am using the following code</p>
  
  <pre><code>for (i in 2:4) {
      jpeg(paste("C:/Data/myplot",i,".jpg"))
           ymin&lt;-min(mydf1[,i],mydf2[,i])
           ymax&lt;-max(mydf1[,i],mydf2[,i])
           plot(mydf1[,1],mydf1[,i],ylim=c(ymin,ymax),xlab="id",ylab=colnames(mydf)[i])
           points(mydf2[,1],mydf2[,i],pch=2)
           legend("topright",c("mydf1","mydf2"),pch=c(1,2))     
           dev.off()
  }
  </code></pre>
  
  <p>My problem is that <strong>I would like to get all three different graphs, (id vs a (mydf1 and mydf2) , id vs b(mydf1 and mydf2), id vs c(mydf1 and mydf2) in one figure.(something like 2 along the first row of the figure and the third one in the second row with legend)</strong> I tried the following </p>
  
  <pre><code>jpeg("C:/Data/myplot.jpg")
      par(mfrow=c(2,2))
  for (i in 2:4) { 
      ymin&lt;-min(mydf1[,i],mydf2[,i])
      ymax&lt;-max(mydf1[,i],mydf2[,i])
      plot(mydf1[,1],mydf1[,i],ylim=c(ymin,ymax),xlab="id",ylab=colnames(mydf)[i])
      points(mydf2[,1],mydf2[,i],pch=2)
      legend("topright",c("mydf1","mydf2"),pch=c(1,2))     
      dev.off()
  }
  </code></pre>
  
  <p>But it didn't work. Any suggestion to do this?
  <strong>p.s: This is the simplified version of my task. Actually I have hundreds of columns, that's why I am using a loop operation</strong></p>
  
  <p><img src="https://i.stack.imgur.com/BQIlo.jpg" alt="enter image description here">
  Sample plot <code>id vs a (mydf1 and mydf2)</code> plotted on the same graph</p>