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

如何使用ggplot2修改森林图中Periodontitis (Yes)的钻石标记颜色

ggplot森林图高亮特定变量钻石标记的实现方法

要修改森林图中「牙周炎(是)」对应的钻石标记颜色,只需在geom_point中通过颜色映射结合手动颜色设置即可实现,以下是修改后的完整代码:

# 变量因子化与排序
dataset_unstratified$variables <- factor(dataset_unstratified$variables
                                         , levels = c("截距(骨骼肌质量指数)","牙周炎(是)", "性别(男)", "年龄", "体重指数", "吸烟者", "曾吸烟者",
                                                      "糖尿病","前驱糖尿病","教育程度(低)","教育程度(中)","每日能量摄入",
                                                      "每日蛋白质摄入", "维生素D2和D3", "骨密度"))
dataset_unstratified <- dataset_unstratified[order(dataset_unstratified$variables), ]

# 标题换行函数
plot_width <- 100
wrapper <- function(x)  {   
  paste(strwrap(x, width = plot_width), collapse = "\n") 
}

# 绘制森林图,高亮特定变量
plot1 <- ggplot(dataset_unstratified, aes(y=variables, x=coefficients)) +
  # 为钻石标记添加颜色映射,关联变量与颜色
  geom_point(aes(color = variables), shape = 18, size = 5) +  
  # 手动设置颜色:将「牙周炎(是)」设为红色,其余变量用黑色(可自行替换颜色值)
  scale_color_manual(values = ifelse(levels(dataset_unstratified$variables) == "牙周炎(是)", 
                                     "red", "black")) +
  # 隐藏颜色图例,避免干扰森林图展示
  guides(color = "none") +
  theme(axis.title.y = element_blank()) +
  xlab("带95%置信区间的β系数") +  
  labs(title = wrapper("a) 骨骼肌质量指数与牙周炎"))+ 
  geom_errorbarh(aes(xmin = `2.5 %`, xmax = `97.5 %`), height = 0.25) +
  geom_vline(xintercept = 0, color = "blue", linetype = "dashed", cex = 1, alpha = 0.5)

关键修改说明:

  • 在geom_point的映射参数中加入color = variables,让标记颜色与变量绑定
  • 用scale_color_manual精准指定目标变量的颜色,其余变量保持默认色
  • 通过guides(color = "none")关闭颜色图例,保持森林图简洁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:25:17