title: R: How to save base plot to a grid object, except from grid.echo()
body: <p>Background: I used a wrapped <code>plot</code> function from the package <code>MatchIt</code> (a package for propensity scoring matching), and find difficulties in putting the graphs together on one page. </p>
  
  <p>My solution: To convert the plots to grid objects first (using <code>grid.echo</code> and <code>grid.grab</code> from <code>gridGraphics</code> package), and then use <code>grid.arrange</code> from <code>gridExtra</code> package to arrange them.</p>
  
  <p>The problem: when using <code>grid.echo</code>, an error occurs: "Error in unit(x, default.units) : 'x' and 'units' must have length > 0". </p>
  
  <p>I figured out that this comes from the fact that part of the graph has all <code>FALSE</code> values. Instead of trying to hack the <code>grid.echo</code> function or the <code>plot</code> function, I would like to ask if there is another way of saving the <code>base plot</code> as <code>grobs</code> objects?</p>
  
  <p>Here is a minimal reproducible example:</p>
  
  <pre><code>### Generate data and the model
  set.seed(10)
  df &lt;- data.frame(y=sample(c(0,1),20,replace=TRUE),x1=rnorm(20),x2=1:20)
  library(MatchIt)
  m.out &lt;- matchit(y~x1+x2,data=df,method='nearest',replace=TRUE,ratio=2,discard="treat") 
  ### This one is OK because "discard" is set, so that the plot has none empty values in all parts    
  m.out_none &lt;- matchit(y~x1+x2,data=df,method='nearest',replace=TRUE,ratio=2,discard="none") 
  ### This one is NOT OK because "discard" is not set, so part of the plot is empty.
  
  ### function to convert base plot to grid objects
  library(gridGraphics)
  grab_grob &lt;- function(){
      grid.echo()
      grid.grab()
  }
  
  plot(m.out_none,interactive=FALSE,type='jitter')
  p1 &lt;- grab_grob() ### Error here
  plot(m.out,interactive=FALSE,type='jitter')
  p2 &lt;- grab_grob() ### No errors
  </code></pre>