如何用R包forestploter指定森林图特定列的对齐方式?
森林图指定列文本居中对齐失效的解决思路
需求说明
需要将森林图中所有文本列设为左对齐,仅**"Direction of effect size from other study"**列(对应数据框第4列)居中对齐。示例数据与现有代码如下:
示例数据
df <- tibble(Outcome="CAD", Exposure="CpG", Gene = "XYZ", "Direction of effect size from other study" ="+", OR = 0.93, OR_loci = 0.90, OR_upci = 0.96, "OR (95% CIs)" = "0.93 (0.90, 0.96)", " " = " ")
现有配置与绘图代码
# 1: 通用样式配置 tm <- forest_theme(base_size = 10, # 设置文本大小 refline_col = "#969696", # OR=1参考线颜色 refline_lty = 'solid', # 参考线线型 ci_lwd = 1.9, # 置信区间线宽 ci_Theight = 0.2, # 置信区间T型端点高度 core=list(bg_params=list(fill=c(rep('#ffffff',length.out=1)))), title_just = 'center', # 标题居中 arrow_type = "closed", legend_name = 'Method', ci_col = '#440154', arrow_label_just = "end", core= list(padding=unit(c(4,3), 'mm')), colhead=list(fg_params=list(hjust=0.5, x=0.5)) # 表头居中 ) # 2: 森林图绘制 p <- forest(df[,c(1:4,9,8)], est = df$OR, lower = df$OR_loci, upper = df$OR_upci, ci_column = 5, # 森林图所在列 ref_line = 1, ticks_at = c(0.9,0.95,1,1.05), xlab='OR', xlim = c(0.9, 1.05), arrow_lab = c("Protective effect", "Increases risk"), theme=tm) # 3: 后续编辑 # 添加表头下边框 g <- add_border(p, part = "header", row = 0, gp = gpar(lwd = 2)) g <- add_border(g, part = "header", row = 1, gp = gpar(lwd = 2)) g <- add_border(g, part = "body", row=2, gp=gpar(lwd=2)) # 设置第3列文本为斜体 g <- edit_plot(g, col=3, part='body', gp=gpar(fontface="italic"))
失败尝试
尝试以下代码设置第4列居中对齐但未生效:
# 失效代码 g1 <- edit_plot(g, col=4, part='body', which = 'text', gp= gpar(just='center'))
解决思路
原因分析
gpar()中没有just参数,文本水平对齐需使用hjust参数,同时需要明确指定文本在列内的中心位置。
方法1:通过edit_plot修正
修改失效代码,使用hjust=0.5并指定x为列的相对中心坐标:
g1 <- edit_plot(g, col=4, part='body', which = 'text', gp= gpar(hjust=0.5), x = unit(0.5, "npc")) # npc为相对坐标,0.5代表列的中心位置
方法2:在主题中预先配置(推荐)
在forest_theme的core参数中,针对每一列设置水平对齐规则,一次性实现需求,无需后续额外编辑:
tm <- forest_theme(base_size = 10, refline_col = "#969696", refline_lty = 'solid', ci_lwd = 1.9, ci_Theight = 0.2, core=list( bg_params=list(fill=c(rep('#ffffff',length.out=1))), padding=unit(c(4,3), 'mm'), # 针对5列设置hjust:前3列左对齐,第4列居中,第5列左对齐 fg_params=list(hjust=c(0,0,0,0.5,0)) ), title_just = 'center', arrow_type = "closed", legend_name = 'Method', ci_col = '#440154', arrow_label_just = "end", colhead=list(fg_params=list(hjust=0.5, x=0.5)) )
使用该主题绘制的森林图会直接应用对齐设置,无需再单独调整第4列。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

