title: Is combining two ggplots with same X vector poor practice/style?
body: <p>Edit Note: My original minimal working example did not accurately reflect my question. Two answers were posted that are great references, but were misguided by my example. For more info, see my comment on r2evan's answer. I've since edited the example. Thanks!</p>
  
  <hr>
  
  <p>I recently found myself in a position where I wanted to merge two ggplot objects. <code>plot1</code> and <code>plot2</code> had the same <code>x</code> values, and I just wanted to take the <code>y</code> values from <code>plot2</code> and throw them onto <code>plot1</code>'s backbone. </p>
  
  <p>It's super simple, so I assumed something like it already existed, but I couldn't find anything. Considering how well-developed R is, I assume either (1) this does exist, and I just haven't found it, or (2) what I'm doing is poor practice/style. Could you let me know which one it is and, if the latter, why should I avoid doing this?</p>
  
  <p>(Actual situation: I have a method in a package that returns a nicely-formatted ggplot object. I want to run that method with a bunch of different objects, but combine the output onto one plot. I would use this helper function to accumulate all of the plots into one)</p>
  
  <hr>
  
  <p><strong>Minimal working example</strong></p>
  
  <p>Okay, so not a fully-working example anymore, I suppose. Assume that the "mysteryObject" class has been defined, and the <code>plotMystery</code> method works on those objects and makes a dataframe with constant x values, but different y values based on the <code>id</code> field. </p>
  
  <pre><code>object1 &lt;- new("mysteryObject", id=1)
  plot1 &lt;- plotMystery(object1)
  plot1
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/1Sn6p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1Sn6p.png" alt="plot1"></a></p>
  
  <pre><code>object2 &lt;- new("mysteryObject", id=2)
  plot2 &lt;- plotMystery(object2)
  plot2
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/QlK1G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QlK1G.png" alt="plot2"></a></p>
  
  <pre><code>combine_plots &lt;- function(ggplot1, ggplot2, color = black) {
      return(
          ggplot1 +
              geom_line(aes(x = ggplot2$data[,1], y = ggplot2$data[,2]), color = color)  
      )
  }
  
  plot_combined &lt;- combine_plots(plot1, plot2, color = "red")
  plot_combined
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/yTUXm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yTUXm.png" alt="plot_combined"></a></p>