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

求助:使用ggplot2制作层级正确的全州/两州stacked bar plot

解决方案:修正堆叠条形图顺序并实现全州版本

问题根源

你的代码堆叠顺序不符合要求,是因为Metric列属于普通字符型,ggplot默认按字母顺序排序,导致层级混乱。解决的核心是将Metric设置为有序因子,明确指定从下到上的堆叠顺序:5th Percentile → Mean → 95th Percentile。


修正后的两州版本代码

# 构造数据时直接将Metric设为有序因子
data <- data.frame(
  State = rep(c("All India", "Punjab"), each = 3),
  Metric = factor(rep(c("5th Percentile", "Mean", "95th Percentile"), 2),
                  levels = c("5th Percentile", "Mean", "95th Percentile"),
                  ordered = TRUE),
  Value = c(163, 217, 271, 183, 243, 302)
)

ggplot(data, aes(x = State, y = Value, fill = Metric)) +
  geom_bar(stat = "identity") +
  geom_text(aes(label = Value), position = position_stack(vjust = 0.5)) +
  scale_fill_manual(values = c("5th Percentile" = "orange", "Mean" = "blue", "95th Percentile" = "green")) +
  labs(title = "Stacked Bar Plot for All India and Punjab", 
       x = "State", 
       y = "Values", 
       fill = "Metric") +
  theme_minimal()

全州版本代码

先将原始宽格式数据转换为ggplot适用的长格式,同时设置有序因子保证堆叠顺序:

# 构造原始数据集
State <- c("All India", "Arunachal Pradesh", "Gujarat", "Jammu & Kashmir", "Madhya Pradesh", "Maharashtra", "Meghalaya", "Mizoram", "Orissa", "Punjab", "Tamil Nadu", "Uttar Pradesh", "West Bengal")
Mean <- c(217, 227, 214, 217, 217, 204, 209, 215, 223, 243, 220, 230, 210)
Percentile_5th <- c(163, 193, 162, 185, 177, 146, 169, 173, 167, 183, 156, 163, 170)
Percentile_95th <- c(271, 262, 265, 249, 258, 261, 249, 257, 280, 302, 284, 297, 249)

# 转成长格式数据,并设置Metric为有序因子
all_states_data <- tidyr::pivot_longer(
  data.frame(State, Mean, Percentile_5th, Percentile_95th),
  cols = -State,
  names_to = "Metric",
  values_to = "Value"
) %>%
  dplyr::mutate(
    Metric = factor(Metric,
                    levels = c("Percentile_5th", "Mean", "Percentile_95th"),
                    labels = c("5th Percentile", "Mean", "95th Percentile"),
                    ordered = TRUE)
  )

# 绘制堆叠条形图
ggplot(all_states_data, aes(x = State, y = Value, fill = Metric)) +
  geom_bar(stat = "identity") +
  geom_text(aes(label = Value), position = position_stack(vjust = 0.5), size = 3) +
  scale_fill_manual(values = c("5th Percentile" = "orange", "Mean" = "blue", "95th Percentile" = "green")) +
  labs(title = "Stacked Bar Plot for All States", 
       x = "State", 
       y = "Values", 
       fill = "Metric") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) # 旋转x轴标签避免重叠

关键说明

  • 有序因子的levels顺序决定了堆叠的层级,排在前面的会在最下方
  • 全州版本使用pivot_longer转换数据格式,比手动构造更高效且不易出错
  • 添加x轴标签旋转是为了避免州名过长导致的重叠问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 18:57:43