You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot2水平误差棒图中添加Y轴加粗分组标题及右侧CI标签列

实现代码

首先安装依赖包(如果未安装):

install.packages("ggh4x")

完整绘图代码如下:

library(tidyverse)
library(ggplot2)
library(ggh4x)

# 预处理数据,添加分组信息和y轴顺序
mydata_proc <- mydata %>%
  mutate(
    # 定义变量所属分组,非吸烟组的分组留空不显示
    var_group = case_when(
      str_detect(term, "smoking|Smoking") ~ "Smoking status",
      TRUE ~ ""
    ),
    # 保持和原代码一致的y轴顺序
    y_pos = fct_rev(term)
  )

ggplot(data=mydata_proc, 
       aes(x=estimate, 
           y=y_pos, 
           color=model)) + 
  geom_point(position=position_dodge(width=0.3)) + 
  geom_errorbarh(aes(xmin=conf_low, xmax=conf_high, height=0.15), 
                 position=position_dodge(width=0.3)) +
  # ========== 需求1:添加Y轴分组标题 ==========
  scale_y_discrete(
    guide = guide_axis_nested(
      # 设置分组标题格式为加粗
      theme = theme(axis.text.y.top = element_text(face = "bold", hjust = 0)),
      # 调整分组标题和下方标签的间距
      nested_offset = unit(2, "pt")
    )
  ) +
  # ========== 需求2:右侧添加label列 ==========
  geom_text(
    aes(label = label, x = max(conf_high, na.rm = T) + 0.3),
    position = position_dodge(width = 0.3),
    hjust = 0, size = 3.5,
    show.legend = F
  ) +
  # 扩展x轴范围,给右侧标签留出足够空间
  expand_limits(x = max(mydata_proc$conf_high, na.rm = T) + 1.2) +
  # 可选:优化主题,去掉右侧多余的刻度线
  theme_classic() +
  labs(y = NULL)

实现说明

  • 需求1的嵌套Y轴标题通过ggh4x包的guide_axis_nested实现,无需新增数据集行,可直接调整分组标题和子标签的间距,避免间距过大的问题,同时支持自定义标题格式(如加粗)。
  • 需求2的右侧标签通过geom_text实现,x坐标设置为比置信区间最大值稍大的位置,使用和点、误差棒一致的position_dodge参数保证对齐,扩展x轴范围避免标签被截断。

内容的提问来源于stack exchange,提问作者tcvdb1992

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 06:15:01