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

在ggplot2中调整图例顺序与堆叠条形顺序一致(反转abcd为dcba)

调整ggplot2堆叠条形图的图例顺序与条形顺序一致

方法1:修改数据的因子水平

通过将cat列转换为因子,并指定levels为c('d','c','b','a'),让填充色的顺序直接匹配条形的堆叠顺序,同时可简化position参数:

plot_data <- data.frame(cat=c('a','b','c','d'),value=c(1:4))
# 修改cat为因子,指定顺序为d、c、b、a
plot_data$cat <- factor(plot_data$cat, levels = c('d','c','b','a'))

plot_data %>% ggplot(aes(x='1',y=value,fill=cat))+
  geom_bar(stat='identity', position = position_stack())+
  geom_text(aes(label=value), position = position_stack(vjust=0.5))

方法2:使用scale_fill_discrete反转图例

无需修改原始数据,直接在ggplot图层中添加scale_fill_discrete(reverse = TRUE)即可反转图例顺序:

plot_data <- data.frame(cat=c('a','b','c','d'),value=c(1:4))
plot_data %>% ggplot(aes(x='1',y=value,fill=cat))+
  geom_bar(stat='identity',position = position_stack(reverse=TRUE))+
  geom_text(aes(label=value),position = position_stack(reverse=TRUE,vjust=0.5))+
  scale_fill_discrete(reverse = TRUE)

方法3:使用guides手动设置图例顺序

通过guides()函数指定fill图例反转,效果与方法2一致:

plot_data <- data.frame(cat=c('a','b','c','d'),value=c(1:4))
plot_data %>% ggplot(aes(x='1',y=value,fill=cat))+
  geom_bar(stat='identity',position = position_stack(reverse=TRUE))+
  geom_text(aes(label=value),position = position_stack(reverse=TRUE,vjust=0.5))+
  guides(fill = guide_legend(reverse = TRUE))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:15:36