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

R语言Yes/No分类堆叠柱状图绘制异常问题求助

解决R语言绘制Yes/No堆叠柱状图的三个问题

修正后的完整代码

library(tidyverse)

# 重构数据框:修正数据类型+指定项目顺序
ic <- data.frame(
  items = factor(c("item1", "item2", "item3", "item4", "item5", 
                   "item6", "item7","item8", "item9", "item10", 
                   "item11", "item12"),
                 levels = paste0("item", 1:12), ordered = TRUE),
  yes = as.numeric(c("6", "6", "7", "4", "2", "6", "6", "8", "2", 
                     "3", "7", "6")), 
  no = as.numeric(c("2", "2", "1", "4", "6", "2", "2", "0", "6", "5",
                    "1", "2"))
)

# 绘制堆叠柱状图
ic %>%
  pivot_longer(cols = -items, names_to = "success", values_to = "value") %>%
  mutate(success = factor(success, levels = c("yes", "no"))) %>%
  ggplot(aes(x = items, y = value, fill = success)) + 
  geom_col(position = "stack") +
  coord_flip() +
  labs(title = "Items People Use", x = "Items", y = "# of individuals") + 
  scale_fill_brewer("Response", palette = "Spectral")

问题拆解与解决逻辑

  • 数值超出总人数(问题b)
    原数据中yes和no列是字符格式(带引号的数值),ggplot会默认统计字符的出现次数而非直接使用数值。只需用as.numeric()将这两列转为数值型,就能正确堆叠实际人数。

  • Yes/No显示顺序混乱(问题a)
    数据转换后success列默认按字母排序(no在前),通过factor(success, levels = c("yes", "no"))强制指定显示顺序;同时配合数值型转换,保证堆叠逻辑正确。

  • Items未按数字顺序排列(问题c)
    字符型的items会按字符串排序(item10会排在item2之前),将其转为有序因子,通过levels = paste0("item", 1:12)明确指定item1到item12的排列顺序,coord_flip()后就能保持正确的纵向排序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 12:15:28