如何在R ggplot2中按DVA份额从低到高排序堆叠条形图?
按DVA份额排序堆叠条形图的解决方案
问题场景
现有长格式数据,需绘制堆叠条形图,并按DVA份额从低到高对Industry排序:
data <- data.frame( Measure = c("DVA", "FVA", "DVA", "FVA", "DVA", "FVA"), Industry = c("Manufacturing", "Manufacturing", "Services", "Services", "Agriculture", "Agriculture"), Share = c(10, 90, 20, 80, 30, 70) )
现有代码未实现需求排序:
ggplot(data, aes(x = Industry, y = Share, fill = Measure)) + geom_bar(stat = "identity") + coord_flip()
解决步骤
- 从数据中筛选
Measure == "DVA"的行,按Share升序排序后提取Industry,得到目标排序顺序 - 将原数据的
Industry列转换为按上述顺序排列的因子 - 基于转换后的数据绘制图表
完整代码
library(ggplot2) # 提取DVA份额并排序,生成Industry的目标顺序 sorted_industry <- data[data$Measure == "DVA", ] |> arrange(Share) |> pull(Industry) # 将Industry转换为指定顺序的因子 data$Industry <- factor(data$Industry, levels = sorted_industry) # 绘制符合排序要求的堆叠条形图 ggplot(data, aes(x = Industry, y = Share, fill = Measure)) + geom_bar(stat = "identity") + coord_flip()
效果说明
转换因子顺序后,Industry会按照DVA份额从10(Manufacturing)→20(Services)→30(Agriculture)的顺序排列,堆叠条形图的呈现逻辑符合需求。
内容的提问来源于stack exchange,提问作者amy
相关产品推荐
相关产品推荐

