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

能否在ggplot的X轴刻度标签中添加各水平的频数?

实现X轴标签添加对应水平频数的方案

完全可行,具体实现步骤如下:

  • 统计各水平的频数
    先对目标变量Question1_3l的每个水平计数,用base R的table()函数即可:

    freq_table <- table(dt$Question1_3l)
    

    示例数据中会得到结果:1:1, 2:1, 3:2。

  • 生成带换行的X轴标签
    把原标签和频数用\n拼接,形成“标签\nn=X”的格式:

    x_labels <- paste(
      c("Dissatisfied", "Neutral", "Satisfied"),
      paste0("n=", freq_table),
      sep = "\n"
    )
    
  • 替换ggplot中的刻度标签参数
    将scale_x_discrete里的labels替换为生成的x_labels,完整代码如下:

dt <- structure(list(Question1 = c("1", "5", "4", "4"), 
                     Question2 = c("2", "5", "4", "4"), 
                     Question3 = c("1", "3", "2", "4"),
                     Question1_3l = c("3", "3", "2", "1"),
                     Question2_3l = c("2", "3", "1", "2"),
                     Question3_3l = c("1", "3", "2", "1")),
                class = c("data.frame"), 
                row.names = c(NA, -4L))

# 统计频数
freq_table <- table(dt$Question1_3l)
# 生成带频数的X轴标签
x_labels <- paste(
  c("Dissatisfied", "Neutral", "Satisfied"),
  paste0("n=", freq_table),
  sep = "\n"
)

ggplot(dt, aes(as.factor(Question1_3l)),  na.rm=T) +                           
  geom_bar(aes(y = (..count..)/sum(..count..)), fill = "#005A9B") +
  geom_text(aes(y = ((..count..)/sum(..count..)), label = scales::percent((..count..)/sum(..count..))), stat = "count", vjust = -0.25) +
  scale_y_continuous(labels = scales::percent) +
  scale_x_discrete(breaks = c(1, 2, 3), labels = x_labels) +
  scale_fill_brewer(palette = "Set2")+ 
  labs(title = "", 
       subtitle = paste("Number of observations: ", nrow(dt)),
       x="", 
       y = "Disabled", 
       color = "Unemployed")

运行后X轴刻度会自动显示每个水平的标签,换行后展示对应观测数,和副标题的总观测数逻辑一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:46:06