An error with grid.echo() when part of the plot is empty
Background: I used a wrapper plot function from the package MatchIt (a package for propensity scoring matching), and find difficulties in putting the graphs together on one page.
My solution: To convert the plots to grid objects first (using grid.echo and grid.grab), and then use grid.arrange to arrange them.
The problem: when using grid.echo, an error occurs: "Error in unit(x, default.units) : 'x' and 'units' must have length > 0". But the base plot is completely normal, the error only occurs when I try to save the plot as a grid plot.
I figured out that this comes from the fact that part of the graph has all FALSE values. Is there any workaround I could do on this?
Here is a minimal reproducible example:
### Generate data and the model
set.seed(10)
df <- data.frame(y=sample(c(0,1),20,replace=TRUE),x1=rnorm(20),x2=1:20)
library(MatchIt)
m.out <- 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 <- 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 <- function(){
grid.echo()
grid.grab()
}
plot(m.out_none,interactive=FALSE,type='jitter')
p1 <- grab_grob() ### Error here
plot(m.out,interactive=FALSE,type='jitter')
p2 <- grab_grob() ### No errors
Thanks for the report and excellent diagnosis. I have pushed a fix (that works for your example at least). Note that if you want to combine a couple of these plots together, you might want to use something like ...
grid.newpage()
pushViewport(viewport(y=.5, height=.5, just="bottom"))
grid.echo(function() plot(...))
... rather than your grid.echo() then grid.grab() approach, so that the plot that you are echoing is drawn within the correct sized region (otherwise what you grab will probably not fit what you draw into).
Hope that helps!
Thanks a lot for the fix and it works for me now. Also for the guidance because I'm very new to grid system. Thanks!