R语言绘制Bland-Altman图添加LoA/均值标注并修改虚线颜色
R语言BlandAltmanLeh包Bland-Altman图自定义修改方案
可直接通过提前计算统计量、覆写ggplot图层的方式实现LoA/均值标注、参考线改色,不需要修改包源码,步骤如下:
- 先计算两组测量值的差值均值、上下95%一致性界限(LoA)的具体数值,同时取x轴最大值作为标注的横向定位参考
- 用
geom_hline覆写包默认生成的参考线图层,自定义虚线颜色、粗细参数 - 用
annotate文本注释层,把三个统计量的数值标注在对应参考线的右侧位置
完整可运行代码如下:
library(BlandAltmanLeh) library(ggplot2) # 示例数据,实际使用时替换为你自己的MA_subset数据集即可 MA_subset <- structure(list( HF_Uhr = c(66L, 62L, 62L, 63L, 70L, 62L, 69L, 62L, 60L, 62L, 68L, 61L,72L, 74L, 79L, 55L, 71L, 70L, 85L, 84L, 64L, 69L, 69L, 74L, 79L, 63L, 77L, 79L, 85L, 73L), HF_VNS = c(65.3, 61.4, 60.8, 62.9, 69.4, 61.1, 68.4, 62.6, 59.5, 62.9, 68.4, 60.1, 78.2, 73.1, 78.8, 58.8, 68.5, 70.6, 84.4, 84.7, 61.3, 69.4, 67.4, 82.2, 72.8, 62.6, 77.4, 78.8, 87.2, 73.2)), row.names = c(NA, 30L), class = "data.frame" ) # 计算绘图需要的统计量 diff_val <- MA_subset$HF_Uhr - MA_subset$HF_VNS mean_diff <- mean(diff_val, na.rm = TRUE) # 差值均值 lower_loa <- mean_diff - 1.96*sd(diff_val, na.rm = TRUE) # 95%下一致性界限 upper_loa <- mean_diff + 1.96*sd(diff_val, na.rm = TRUE) # 95%上一致性界限 x_pos <- max((MA_subset$HF_Uhr + MA_subset$HF_VNS)/2, na.rm = TRUE) # 标注的横向位置 # 生成基础Bland-Altman图 HF_plot1 <- bland.altman.plot(MA_subset$HF_Uhr, MA_subset$HF_VNS, graph.sys = "ggplot2", mode = 1) # 自定义图层调整 HF_plot1_final <- HF_plot1 + # 覆写默认参考线,可自行修改颜色值、线宽 geom_hline(yintercept = mean_diff, color = "#2c5aa0", linetype = "dashed", linewidth = 0.8) + geom_hline(yintercept = lower_loa, color = "#c82423", linetype = "dashed", linewidth = 0.8) + geom_hline(yintercept = upper_loa, color = "#c82423", linetype = "dashed", linewidth = 0.8) + # 添加数值标注,可自行调整文本大小、小数位数 annotate("text", x = x_pos, y = mean_diff, label = paste0("Bias: ", round(mean_diff,2)), vjust = -0.6, size = 3.5) + annotate("text", x = x_pos, y = lower_loa, label = paste0("Lower LoA: ", round(lower_loa,2)), vjust = -0.6, size = 3.5) + annotate("text", x = x_pos, y = upper_loa, label = paste0("Upper LoA: ", round(upper_loa,2)), vjust = -0.6, size = 3.5) + # 原有标题、坐标轴设置 ggtitle("Bland-Altman-Plot for Heart Frequency")+ theme(plot.title = element_text(size=15, face= "bold", hjust = 0.5))+ labs(x="Means of HF between Garmin Venu 2 & VNS analysis [bpm]", y ="Difference of HF between Garmin Venu 2 & VNS analysis [bpm]")+ theme(axis.title.x = element_text(size= 9, hjust = 0.5))+ theme(axis.title.y = element_text(size= 8, hjust = 0.5, lineheight= 1)) # 输出图片 print(HF_plot1_final)
调整提示:如果右侧标注被图边框截断,可以在图层调整部分末尾添加
coord_cartesian(clip = "off")关闭裁剪,或用xlim()适当扩大x轴右侧范围留出标注空间;参考线颜色、标注文本内容都可以按需求修改。
内容的提问来源于stack exchange,提问作者Christine
相关产品推荐
相关产品推荐

