You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fixest包生成图形合并遇阻:报错及保存难题求解

合并fixest图形并保存的可行方案

问题背景

尝试合并fixest包生成的iplot和coefplot图形时,使用ggpubr::ggarrange出现对象转换错误;用par()排版虽能展示布局,但无法直接保存合并后的图形,recordPlot重放时也会丢失布局设置。原代码及运行警告如下:

原代码

library("fixest")
library("ggpubr")

data(base_did)
base_inter = base_did

est_did = feols(y ~ x1 + i(period, treat, 5) | id+period, base_inter)
pl1 <- iplot(est_did)
pl2 <- coefplot(est_did)

plot_list <- list(pl1, pl2)
combined_plot <- ggarrange(plotlist = plot_list, ncol = 2)

运行警告

Warning messages:
1: In as_grob.default(plot) :
  Cannot convert object of class list into a grob.
2: In as_grob.default(plot) :
  Cannot convert object of class list into a grob.

临时排版代码(无法保存):

par(mfrow = c(2, 2))
iplot(est_did)
coefplot(est_did)
iplot(est_did)
coefplot(est_did)
par(mfrow = c(1, 1))

解决方案

方案1:使用fixest内置的merge_plots函数

fixest自带专门的图形合并工具,支持布局设置,且能直接保存合并后的图形:

library(fixest)

data(base_did)
est_did = feols(y ~ x1 + i(period, treat, 5) | id+period, base_did)

# 生成可被合并的ggplot对象(必须加keep_plot = TRUE)
pl1 <- iplot(est_did, keep_plot = TRUE)
pl2 <- coefplot(est_did, keep_plot = TRUE)

# 2列布局合并图形
combined_plot <- merge_plots(list(pl1, pl2), ncol = 2)

# 保存图形
ggsave("combined_fixest_plots.png", combined_plot, width = 12, height = 6)

方案2:用ggplotify转换基础绘图为ggplot对象

若需与其他ggplot图形混合排版,可将fixest的基础绘图转为ggplot对象后,用ggpubr或patchwork合并:

library(fixest)
library(ggpubr)
library(ggplotify)

data(base_did)
est_did = feols(y ~ x1 + i(period, treat, 5) | id+period, base_did)

# 转换基础绘图为ggplot对象
pl1 <- as.ggplot(iplot(est_did))
pl2 <- as.ggplot(coefplot(est_did))

# 合并并保存
combined_plot <- ggarrange(pl1, pl2, ncol = 2)
ggsave("combined_plots_ggplotify.png", combined_plot, width = 12, height = 6)

方案3:用grid包直接组合基础绘图

针对纯基础绘图场景,可直接在图形设备中用grid包布局并保存:

library(fixest)
library(grid)

data(base_did)
est_did = feols(y ~ x1 + i(period, treat, 5) | id+period, base_did)

# 打开图形设备并设置1行2列布局
png("combined_grid_plots.png", width = 1200, height = 600)
pushViewport(viewport(layout = grid.layout(1, 2)))

# 在第一个格子绘制iplot
pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 1))
iplot(est_did)
popViewport()

# 在第二个格子绘制coefplot
pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 2))
coefplot(est_did)
popViewport()

# 关闭设备完成保存
dev.off()

内容的提问来源于stack exchange,提问作者yacx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 22:00:59