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

使用plot_coefs绘制15个回归模型系数仅显示12个的问题咨询

问题

我运行了15个回归模型(本质为同一回归、变量相同,仅年份不同),使用plot_coefs绘制系数。但绘图中仅显示前12个模型的系数,图例却显示全部15个模型。我的代码如下:

cdu_1965b <- glm(cduwahl ~  alter + bildung + mann + konfessi 
                 , data = Wahl1965, family = "binomial")

cdu_1969b <- glm(cduwahl ~  alter + bildung + mann + konfessi 
                 , data = Wahl1969, family = "binomial")

# 其余13个模型代码类似
library(jtools)
plot_coefs (cdu_1965b,cdu_1969b, ...other models..., colors = "Rainbow", omit.coefs = c("(Intercept)", "altermittel", "alteralt", "bildunghoch", "bildungmittel", "bildungalt", "mann"))

请问plot_coefs是否存在可绘制的模型数量上限?还有其他解决办法吗?

解决方法

plot_coefs(jtools包中的函数)默认确实设置了模型数量上限——最多显示12个模型,这就是你只看到前12个模型系数的原因。

有两种可行的解决方式:

  • 修改model.limit参数:直接在plot_coefs中添加model.limit = 15参数,强制显示全部15个模型。示例代码:

    plot_coefs(cdu_1965b, cdu_1969b, ...other models..., 
               colors = "Rainbow", 
               omit.coefs = c("(Intercept)", "altermittel", "alteralt", "bildunghoch", "bildungmittel", "bildungalt", "mann"),
               model.limit = 15)
    
  • 手动提取系数后自定义绘图:如果修改参数仍有问题,可借助broom和ggplot2手动处理数据并绘图,灵活性更高:

    1. 将所有模型存入列表并命名:
      model_list <- list(cdu_1965b, cdu_1969b, ...other models...)
      names(model_list) <- c("1965", "1969", ...) # 对应各模型的年份
      
    2. 提取系数及置信区间:
      library(broom)
      library(dplyr)
      coef_df <- bind_rows(lapply(model_list, function(x) {
        tidy(x, conf.int = TRUE) %>%
          filter(!term %in% c("(Intercept)", "altermittel", "alteralt", "bildunghoch", "bildungmittel", "bildungalt", "mann"))
      }), .id = "year")
      
    3. 用ggplot2绘制系数图:
      library(ggplot2)
      ggplot(coef_df, aes(x = term, y = estimate, color = year, group = year)) +
        geom_point(position = position_dodge(width = 0.5)) +
        geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = 0.2, position = position_dodge(width = 0.5)) +
        coord_flip() +
        scale_color_brewer(palette = "Rainbow") +
        theme_minimal()
      

内容的提问来源于stack exchange,提问作者Johannes H.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 00:13:21