You need to enable JavaScript to run this app. R ggplot分组堆叠条形图堆栈顺序、横置及数值标签设置问题
优惠活动
大模型
产品
解决方案
定价
更多

R ggplot分组堆叠条形图堆栈顺序、横置及数值标签设置问题

可复现解决方案

首先修正原代码中gender分类赋值的笔误,再按需求调整参数即可:

核心调整逻辑

  • 调整堆叠顺序:将gender转换为有序因子,手动指定层级为Agree→Neutral→Disagree,ggplot会严格按照因子层级顺序堆叠
  • 切换横向布局:调用coord_flip()翻转坐标轴,同时将分面改为纵向排列,给超长分类标签留出充足的水平展示空间
  • 添加条形内部数值:新增geom_text()层,使用position_stack(vjust = 0.5)参数让数值标签居中显示在对应堆叠块内部

完整可运行代码

test  <- data.frame(person=c("8.3. The number of people coming to me \n me, who
                             are who want pizza are too many \n,
                             and too aggressive.", "group 2", "group 3", "5", "6"), 
                    value1=c(100,150,120,100,100),  # Agree   
                    value2=c(25,30,45,100,100) ,    # Neutral
                    value3=c(25,30,45,100,100),     # Disagree
                    value4=c(100,120,150,100,100),  # Agree
                    value5=c(10,12,15,100,100),     # Neutral
                    value6=c(50,40,70,100,100))     # Disagree

library(reshape2) 
library(ggplot2)
library(dplyr)

melted <- melt(test, "person")

melted$cat <- ''
melted[melted$variable %in% paste0("value",1:3),]$cat <- "GP"
melted[melted$variable %in% paste0("value",4:6),]$cat <- "LW"

# 修正分类赋值笔误,同时设置为有序因子控制堆叠顺序
melted$gender <- factor(
  case_when(
    melted$variable %in% paste0("value",c(1,4)) ~ "Agree",
    melted$variable %in% paste0("value",c(2,5)) ~ "Neutral",
    melted$variable %in% paste0("value",c(3,6)) ~ "Disagree"
  ),
  levels = c("Agree", "Neutral", "Disagree") # 此处顺序即为堆叠顺序
)

ggplot(melted, aes(x = cat, y = value, fill = gender)) + 
  geom_bar(stat = 'identity', position = 'stack') +
  # 添加堆叠块内部数值标签
  geom_text(aes(label = value), position = position_stack(vjust = 0.5), size = 3) +
  # 纵向分面适配横向条形
  facet_grid(person ~ .) + 
  # 翻转坐标轴变为横向布局
  coord_flip() +
  scale_fill_manual(values = c("orangered","green","dodgerblue2")) + 
  theme(panel.background = element_rect(fill = 'white'))

如果需要调整标签大小、分面间距,可对应修改geom_text的size参数、theme中的strip.text、panel.spacing参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 17:54:06