PAYATHON 2026

如何让 ggforestplot 的 dodge 点顺序与图例一致?

数据小陈

结论

ggforestplot 0.1.0 与 ggplot2 4.0.3 一起使用时,position 参数不保证能同时控制点图层和误差条图层的 dodge 顺序。position_dodge() 的排列由 group 的因子 levels 决定,guide_legend(reverse = TRUE) 只会改变图例显示顺序,不会影响 dodge 的计算。要让点的顺序与图例一致,比较稳妥的做法是明确设置绘图用因子的 levels,或者直接用 ggplot2 手工绘制点和误差条。

原因

当 colour 和 shape 都映射到同一个 Age_group 时,dodge 排列依赖这个因子的 levels。图例按 levels 显示,但 ggforestplot 内部可能对点和误差条用了不同的 position,或者没有把 position 传到所有图层。你试过 position_dodge(width = 0.7, reverse = TRUE);如果它只影响其中一个图层,视觉上仍然会错位。

方案一:反转绘图因子,再反转图例显示

保留原始 Age_group 不变,新增一个只用于绘图的因子,把 levels 反过来:

plot_data_test <- plot_data_test %>%
  mutate(
    Age_group_plot = factor(
      Age_group,
      levels = rev(levels(Age_group))
    )
  )

p <- ggforestplot::forestplot(
  df = plot_data_test,
  name = Assay,
  estimate = BETA,
  se = SE,
  pvalue = P_FDR_corrected,
  colour = Age_group_plot,
  shape = Age_group_plot,
  position = position_dodge(width = 0.7)
) +
  scale_colour_discrete(guide = guide_legend(reverse = TRUE)) +
  scale_shape_discrete(guide = guide_legend(reverse = TRUE)) +
  labs(
    colour = 'Age group (range)',
    shape = 'Age group (range)'
  )

这样 dodge 顺序会随新的 levels 翻转。再用 guide_legend(reverse = TRUE) 把图例显示顺序翻回 Full sample combined、Age group 1、Age group 2、Age group 3。colour 和 shape 两个 guide 都要设置。

方案二:手工用 ggplot2 画点和误差条

如果 ggforestplot 内部仍然覆盖 position,直接手工绘制更可控。关键是显式写出 group = Age_group,并让点和误差条共用同一个 position_dodge():

dodge <- position_dodge(width = 0.7)

ggplot(
  data,
  aes(
    y = Assay,
    x = BETA,
    colour = Age_group,
    shape = Age_group,
    group = Age_group
  )
) +
  geom_errorbarh(
    aes(xmin = LCI, xmax = UCI),
    height = 0.2,
    position = dodge
  ) +
  geom_point(size = 2, position = dodge) +
  facet_grid(. ~ Group, scales = 'free', space = 'free') +
  scale_colour_discrete(drop = FALSE) +
  scale_shape_discrete(drop = FALSE) +
  labs(
    x = 'Beta (95% confidence intervals)',
    y = 'Analyte',
    colour = 'Age group (range)',
    shape = 'Age group (range)'
  ) +
  theme_bw()

如果手工绘制后顺序还是相反,再把 dodge 改成 position_dodge(width = 0.7, reverse = TRUE),或者同时反转 Age_group 的 levels。不要在没确认图层的情况下同时使用多种反转,否则图例和点的顺序容易再次弄反。

检查与注意事项

可以用 layer_data(p) 查看各图层实际的 y 坐标,确认点和误差条是否用了同一个 dodge 结果。geom_errorbarh 在新版 ggplot2 中仍然可用,但更推荐 geom_errorbar(orientation = 'y')。确认 Age_group 是 factor,并确保 drop = FALSE 时所有 levels 都保留。不同版本的 ggforestplot 对 position 的透传行为可能不同;升级后如果行为变了,先检查内部图层的 position 是否一致。

备注:内容仅供参考。