如何在R语言ggplot2绘制的森林图中添加RR及95%置信区间文本?
给森林图添加RR与95%置信区间文本标注
步骤1:格式化标注文本
先在数据框中新增一列,将RR值和95%CI格式化为目标文本样式:
# 把RR、95%CI格式化为"数值 (下限, 上限)"的样式,保留两位小数 df3$rr_text <- sprintf("%.2f (%.2f, %.2f)", df3$effect, df3$lower, df3$upper)
步骤2:修改绘图代码添加文本标注
在原有ggplot代码基础上,加入文本标注层,并调整轴范围避免文本被截断:
plot2 <- ggplot(data=df3, aes(y=index, x=effect, xmin=lower, xmax=upper))+ geom_point(shape="diamond", colour="royalblue4", size=5) + geom_errorbarh(height=.2, colour="royalblue4") + # 添加RR和95%CI文本,放在误差条右侧 geom_text(aes(x = upper + 0.03, label = rr_text), hjust = 0, size = 3.5, colour = "black") + scale_y_continuous(breaks=1:nrow(df3), labels=df3$outcome) + # 扩展x轴范围,给标注文本留出空间 scale_x_continuous(limits = c(min(df3$lower)-0.05, max(df3$upper)+0.15)) + labs(title="Adjusted Relative Risk for Complications", x="Relative Risk", y = "Type of complication") + geom_vline(xintercept=0, color='gray', linetype='dashed', alpha=.5) + theme_minimal()+ plots_theme
可选优化:根据数值方向调整文本位置
如果部分RR值为负(误差条在0左侧),可以让负数值的文本放在误差条左侧,避免重叠:
geom_text(aes(x = ifelse(effect > 0, upper + 0.03, lower - 0.03), label = rr_text), hjust = ifelse(effect > 0, 0, 1), size = 3.5)
内容的提问来源于stack exchange,提问作者Darla Carvallo
相关产品推荐
相关产品推荐

