ggplot2分组柱状图顺序与数据框预设不一致问题求助
解决方案
你出现顺序错乱的核心原因有三点:
- x轴映射的
ValueEffects列为字符类型,ggplot默认按字母顺序排序,不会遵循你数据框的原有顺序 - 你仅调整了分组列
variable的因子水平,未同步处理x轴分类的顺序 - y轴映射的
value列为字符类型,无法正确映射柱状高度,也会干扰分组排序逻辑
按如下步骤调整即可:
第一步:预处理数据集,给分类变量设置指定顺序的因子水平,同时转换数值列
# 设置x轴分类顺序 GraphTableIndustry$ValueEffects <- factor(GraphTableIndustry$ValueEffects, levels = c("MM Levered", "Leverage Effect", "MM Unlevered", "Multiple Effect", "Combination Effect", "Operating Improvements", "FCF Effect", "EBITDA Effect", "Revenue Effect", "Margin Effect", "Combination R/M Effect")) # 设置fill分组(图例)顺序 GraphTableIndustry$variable <- factor(GraphTableIndustry$variable, levels = c('Other', 'Medical & Health', 'IT', 'Industrial')) # 将y轴值转为数值型 GraphTableIndustry$value <- as.numeric(GraphTableIndustry$value)
第二步:运行你原本的ggplot绘图代码即可得到符合预期顺序的图表
ggplot(GraphTableIndustry, aes(x = ValueEffects, y = value, fill = variable)) + geom_bar(stat = "identity", position = "dodge") + geom_text(aes(label = value), vjust = -0.5, color = "black", position = position_dodge(width = 0.9), size = 3.5) + theme(axis.line = element_blank(), axis.text.y = element_blank(), axis.text = element_text( size = 10, color = "black"), axis.ticks = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank(), panel.background = element_blank(), panel.border = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), plot.background = element_blank(), legend.text = element_text( size = 10, color = "black"), legend.title = element_blank() ) + theme(legend.position = "bottom") + scale_fill_brewer(palette = "Blues", direction = -1)
内容的提问来源于stack exchange,提问作者bajk2019
相关产品推荐
相关产品推荐

