如何在R的forestplot中为多条垂直线分配独特颜色
解决Forestplot多垂直线的颜色与线型自定义问题
要给forestplot的多条垂直线分别设置颜色和线型,不能直接在单个gpar()里传入向量参数,需要将grid设置为列表形式,每个列表元素对应一条垂直线的位置和样式。
修改后的完整代码
library(dplyr) library(forestplot) df <- data.frame( model_name = rep(c('A','B','C','D'),3), group = c(rep("Qrt 2",4),rep("Qrt 3",4),rep("Qrt 4",4)), mean = c(10, 9.5, 10.5, 11, 5, 4.75, 5.25, 5.05, 2, 1.9, 1.8, 1.7), lower = c(9, 8.5, 9.5, 10, 4, 4, 4.5, 4.25, 1.7, 1.6, 1.7, 1.65), upper = c(11, 10.5, 10.75, 12, 6, 5, 5.5, 5.8, 2.3, 2.2, 1.9, 1.75) ) df |> group_by(group) |> forestplot( title = "Test Forest Plot", labeltext = model_name, boxsize = 0.2, vertices = TRUE, # 关键修改:用列表分别定义每条垂直线的位置和样式 grid = list( structure(df[1,3], gp = gpar(lty = 1, col = "blue")), structure(df[5,3], gp = gpar(lty = 2, col = "green")), structure(df[9,3], gp = gpar(lty = 2, col = "red")) ) ) |> fp_set_style(box = c("blue", "green", "red"), line = c("blue", "green", "red")) |> fp_add_header(model_name = c("Model")) |> fp_add_lines(h_2 = gpar(lwd = 1), h_3 = gpar(lwd = 1), h_4 = gpar(lwd = 1), h_5 = gpar(lwd = 1), h_6 = gpar(lwd = 1))
原理说明
forestplot的grid参数支持两种输入形式:
- 单一数值/数值向量 + 全局
gpar():此时所有垂直线会共用同一套样式(颜色、线型等) - 列表形式:每个列表元素是一个带
gp属性的数值,单独定义对应垂直线的位置和样式,这样就能实现每条线的个性化配置
这样修改后,三条垂直线会分别显示为蓝色实线、绿色虚线、红色虚线,完全匹配需求。
内容的提问来源于stack exchange,提问作者Io Ferenghetti
相关产品推荐
相关产品推荐

