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

如何为modelplot()森林图按正负值设置系数颜色?

解决方案

要实现modelplot()绘制森林图时按系数正负设置不同颜色,核心是利用ggplot的颜色映射功能,针对系数的正负值创建分类变量,再手动指定对应颜色。具体修改代码如下:

library(modelsummary)
library(ggplot2)

modelplot(
    model1,
    coef_omit = 'Interc'
) + 
  # 按系数正负创建颜色分组变量
  aes(color = ifelse(estimate > 0, "Positive", "Negative")) +
  # 手动指定正负对应的颜色(可按需替换)
  scale_color_manual(values = c("Negative" = "#2c3e50", "Positive" = "#e74c3c")) +
  xlim(-0.75, 0.75) +
  theme_gray() +
  labs(
    x = "Coefficient estimates and \n 95 pc confidence intervals",
    color = "Coefficient Sign" # 图例标题
  )

关键说明:

  • 你之前尝试的scale_colour_gradientn()无效,是因为它针对连续数值变量生成渐变颜色,而这里我们需要的是正负分类变量的离散颜色,因此改用scale_color_manual()更合适。
  • 如果存在系数恰好为0的情况,可以扩展判断逻辑:
    aes(color = ifelse(estimate > 0, "Positive", ifelse(estimate < 0, "Negative", "Zero")))
    
    同时在scale_color_manual中添加"Zero" = "#95a5a6"这类颜色值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 11:55:18