Skip to content

An error with grid.echo() when part of the plot is empty #9

@abzhaobo

Description

@abzhaobo

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions