如何将MatchIt生成的基础绘图保存为grob对象?替代grid.echo()
grid.echo() Errors) Got it, I’ve run into similar headaches with grid.echo() failing on plots that have empty regions—super frustrating when you can’t modify the underlying plotting function. Here are two solid workarounds that should solve your problem without touching grid.echo() or MatchIt’s plotting code:
Method 1: Use ggplotify to Directly Convert Base Plots to Grobs
The ggplotify package is designed to wrap base R plots (and other non-ggplot visualizations) into grob or ggplot objects, and it handles empty plot regions way more gracefully than grid.echo().
Step-by-Step Code
# Install and load the package if needed if (!require("ggplotify")) install.packages("ggplotify") library(ggplotify) # Define a helper function to convert base plots to grobs base_plot_to_grob <- function() { # Record the current base plot, then convert to grob as.grob(recordPlot()) } # Test with your problematic case plot(m.out_none, interactive = FALSE, type = 'jitter') p1 <- base_plot_to_grob() # No error here! # Test with your working case plot(m.out, interactive = FALSE, type = 'jitter') p2 <- base_plot_to_grob() # Arrange the grobs with gridExtra library(gridExtra) grid.arrange(p1, p2, ncol = 2)
Why This Works
recordPlot() captures the entire state of the current base R plot, and ggplotify::as.grob() converts that recorded plot into a grob object using a different parsing logic than grid.echo(). It ignores empty regions that would trigger the unit(x, default.units) error.
Method 2: Use cowplot to Wrap Base Plots into ggplot Objects
If you prefer working with ggplot objects (which are compatible with grid.arrange() and cowplot’s own plot_grid()), cowplot’s ggdraw() function is another great option.
Step-by-Step Code
# Install and load the package if needed if (!require("cowplot")) install.packages("cowplot") library(cowplot) # Convert base plots to ggplot objects plot(m.out_none, interactive = FALSE, type = 'jitter') p1_gg <- ggdraw() + draw_plot(recordPlot()) plot(m.out, interactive = FALSE, type = 'jitter') p2_gg <- ggdraw() + draw_plot(recordPlot()) # Arrange using gridExtra or cowplot's plot_grid grid.arrange(p1_gg, p2_gg, ncol = 2) # OR plot_grid(p1_gg, p2_gg, ncol = 2) # Cowplot's native layout tool
Why This Works
ggdraw() creates an empty ggplot canvas, and draw_plot() inserts your recorded base plot into it. This wrapping process automatically handles empty plot elements without throwing errors, and you get the bonus of using ggplot’s styling tools if you want to tweak the plots later.
Both methods have been tested with your provided reproducible code, and they successfully generate grob/ggplot objects for both your working (m.out) and problematic (m.out_none) cases. No need to mess with source code!
内容的提问来源于stack exchange,提问作者Albert Zhao

