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

如何在ggplot加权调查条形图的x轴刻度添加样本量标签

实现方案

两种全自动生成标签的方案,无需手动修改刻度,原生支持换行/层级展示,解决长国名拥挤问题:


方案一:自定义换行刻度标签(完全匹配你期望的展示效果)

步骤1:加载依赖&构造数据

library(tidyverse)

# 你的原始数据,可替换为实际导入的dataframe
df <- tibble(
  抽样权重 = c(400,600,300,500,100,50),
  国家 = rep(c("A","B","C"), each=2),
  性别 = rep(c("男性","女性"),3),
  占比 = c(20,80,30,70,40,60),
  样本量n = c(100,70,45,70,100,70)
)

步骤2:自动生成国家-标签映射表

country_label_map <- df %>%
  group_by(国家) %>%
  summarise(
    # 拼接同国家下的性别+样本量文本
    gender_n_line = str_glue("Male (n = {first(样本量n)}) Female (n = {last(样本量n)})"),
    # 用\n实现换行,生成最终标签
    x_label = str_c(gender_n_line, str_glue("国家{国家}"), sep = "\n")
  ) %>%
  # 转成命名向量,直接供ggplot scale调用
  deframe()

步骤3:绘制分组条形图

ggplot(df, aes(x = 国家, y = 占比, fill = 性别)) +
  geom_col(position = position_dodge(width = 0.9), width = 0.8) +
  # 替换x轴刻度为自动生成的带换行标签
  scale_x_discrete(labels = country_label_map) +
  # 调整x轴文本行高,避免换行后拥挤
  theme(axis.text.x = element_text(hjust = 0.5, lineheight = 1.2)) +
  labs(x = NULL)

方案二:嵌套x轴(适合国名较长、国家数量多的场景)

用层级拆分标签,更美观清晰,需要用到ggh4x扩展包:

步骤1:安装加载扩展包

# 首次使用先安装
# install.packages("ggh4x")
library(ggh4x)

步骤2:绘制嵌套轴条形图

ggplot(df, aes(x = interaction(性别, 国家), y = 占比, fill = 性别)) +
  geom_col(width = 0.8) +
  scale_x_discrete(
    guide = guide_axis_nested(
      # 定义两层嵌套标签:上层为性别+样本量,下层为国家
      levels = list(
        str_glue("{ifelse(df$性别=='男性','Male','Female')} (n={df$样本量n})"),
        df$国家
      )
    )
  ) +
  theme(
    axis.text.x = element_text(hjust = 0.5),
    ggh4x.axis.nestline.x = element_line(linewidth = 0.8),
    ggh4x.axis.nesttext.x = element_text(hjust = 0.5)
  ) +
  labs(x = NULL)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:36:03