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

调整ggplot2堆叠条形图层级顺序,使cars层级优先于bicyclis显示

解决堆叠条形图层级顺序问题

你当前的代码存在两个关键问题:

  • 使用了position = "identity",这会让两个类别的条形重叠显示,而非堆叠
  • 虽然已经设置了因子层级,但错误的position参数导致堆叠效果未生效

修改后的代码

library(ggplot2)
library(reshape2)

# Generate artificial data
set.seed(123)
deciles <- rep(1:10, 2)
variable <- rep(c("cars", "bicyclis"), each = 10)
value <- runif(20, min = 0, max = 100)

# Create data frame
df <- data.frame(deciles, variable, value)

df$variable <- factor(df$variable, levels = c("cars", "bicyclis"))

ggplot(df, aes(x = factor(deciles), y = value, fill = variable)) +
  geom_bar(stat = "identity", position = "stack") +  
  scale_fill_manual(values = c("royalblue", "red"))

关键说明

  1. 将position = "identity"改为position = "stack",启用堆叠条形图效果
  2. 你已经正确设置了variable的因子层级c("cars", "bicyclis"),ggplot默认会按照因子层级从下到上堆叠:
    • 蓝色的cars会显示在堆叠的底层(第一层)
    • 红色的bicyclis会显示在堆叠的上层(第二层)

如果后续需要反转堆叠顺序,只需将position改为position_stack(reverse = TRUE)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 20:12:38