title: Plotting two legends side by side or one legend with two columns
body: <p>I have a <code>data.frame</code> that includes x and y values which I want to plot (y vs. x). There are two factors, one with three levels and the other with two levels, to which each points is assigned:</p>
  
  <pre><code>df = data.frame(x=c(1:90),y=runif(90,5,10),pch=c(rep(0,30),rep(5,30),rep(6,30)),col=c(rep("red",45),rep("blue",45)),cell=c(rep("A",30),rep("B",30),rep("C",30)),group=c(rep("p",45),rep("v",45)))
  </code></pre>
  
  <p>As you can see, the factors are: <code>cell</code> and <code>group</code>, with respective levels: <code>c("A","B","C")</code> for <code>cell</code> and <code>c("p","v")</code> for <code>group</code>. I have three different shapes (<code>pch</code>) for the <code>cell</code> factor levels and two different colors for the <code>group</code> factor levels.</p>
  
  <p>I want to plot the <code>df$y</code> vs. <code>df$x</code> points with <code>pch</code> and <code>color</code>s specified according to <code>df$pch</code> and <code>df$col</code> and have two legends side by side: one for the cell factor levels and the other for the group factor levels or one legend with two columns of both factors.</p>
  
  <p>So far this is what I'm playing around with:</p>
  
  <pre><code>plot(df$x,df$y,pch=df$pch,col=as.character(df$col),xlim=c(min(df$x),max(df$x)+5),ylim=c(min(df$y),max(df$y)+2))
  legend("topright",title="Cell",legend=c("A","B","C"),col="black",pch=c(0,5,6),bty="n",border=F)
  legend(x=75,y=12,title="Group",legend=c("p","v"),col=c("red","blue"),lty=c(1,1),bty="n",border=F)
  </code></pre>
  
  <p>Which produces this plot:
  <img src="https://i.stack.imgur.com/JoK3n.png" alt="enter image description here"></p>
  
  <p>Which I'm not happy with since I need to adjust the locations of the two legends to get them properly aligned. I'm wondering whether there's a better, more automatic, way to achieve this. </p>
  
  <p>On the same note, it would be nice to know if there's also an automatic way to figure out how much extra space in the plot is needed to fit the legends and specify that in the <code>xlim</code> and <code>ylim</code> rather than manually adjusting them. </p>
  
  <p>One last thing - if possible I'd prefer a solution that's not ggplot</p>