title: How to create faceted linear regression plot using GGPLOT
body: <p>I have a data frame created the following way.</p>
  
  <pre><code>library(ggplot2)
  
  x &lt;- data.frame(letters[1:10],abs(rnorm(10)),abs(rnorm(10)),type="x")
  y &lt;- data.frame(letters[1:10],abs(rnorm(10)),abs(rnorm(10)),type="y")
   # in reality the number of row could be larger than 10 for each x and y
  
  all &lt;- rbind(x,y)
  colnames(all) &lt;- c("name","val1","val2","type")
  </code></pre>
  
  <p>What I want to do is to create a faceted ggplot that looks roughly like this:</p>
  
  <p><img src="https://i.stack.imgur.com/r3wBT.jpg" alt="enter image description here"></p>
  
  <p>Hence each facet above is the correlation plot of the following:</p>
  
  <pre><code># Top left facet
  subset(all,type=="x")$val1 
  subset(all,type=="y")$val1
  
  # Top right facet
  subset(all,type=="x")$val1 
  subset(all,type=="y")$val2
  
  # ...etc..
  </code></pre>
  
  <p>But I'm stuck with the following code:</p>
  
  <pre><code>p &lt;- ggplot(all, aes(val1, val2))+ geom_smooth(method = "lm")  + geom_point() +
  facet_grid(type ~ ) 
  # Calculate correlation for each group
  cors &lt;- ddply(all, c(type ~ ), summarise, cor = round(cor(val1, val2), 2))
  p + geom_text(data=cors, aes(label=paste("r=", cor, sep="")), x=0.5, y=0.5)
  </code></pre>
  
  <p>What's the right way to do it?</p>