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

在R语言中调整堆叠条形图的堆叠顺序

Fixing Stacked Bar Order & Colors in ggplot2

Hey there! Let's get that stacked bar chart looking exactly how you want it—with Gold (green) at the top, Silver (blue) in the middle, and Bronze (red) at the bottom. The issue you're running into is that ggplot2 uses the factor level order of your Medal column to determine stacking order, not the row order of your dataset. Here's how to fix it step by step:

Step 1: Clean Up Your Data Processing

First, I noticed a small typo in your code (you referenced sorted but your processed data is stored in maingraph2graphdata). Let's tidy up your data pipeline first:

library(dplyr)
library(ggplot2)

# Your original data aggregation (with dplyr best practices)
maingraph2 <- cleaneddataset %>% 
  group_by(NOC, Medal) %>% 
  summarise(MedalCount = sum(MedalCount), .groups = "drop") # Avoids dplyr grouping warnings

# Filter to your top 10 target countries
maingraph2graphdata <- maingraph2 %>%
  filter(NOC %in% c('USA', 'URS', 'SWE', 'ITA', 'HUN', 'GER', 'GDR', 'GBR', 'FRA', 'AUS'))

Step 2: Control Stack Order with Factor Levels

To set the exact stacking sequence, we need to convert Medal into an ordered factor with your desired top-to-bottom order. This tells ggplot exactly how to arrange the stacked segments:

maingraph2graphdata <- maingraph2graphdata %>%
  # Define the order you want (top to bottom: Gold → Silver → Bronze)
  mutate(Medal = factor(Medal, levels = c("Gold", "Silver", "Bronze"), ordered = TRUE))

Step 3: Build the Plot with Custom Colors & Stack Order

By default, ggplot stacks factors from bottom to top based on their level order. We'll use position_stack(reverse = TRUE) to flip this so your first factor level (Gold) appears at the top. Then we'll add your custom color mapping:

ggplot(maingraph2graphdata, aes(x = NOC, y = MedalCount)) +
  geom_col(aes(fill = Medal), width = 0.7, position = position_stack(reverse = TRUE)) +
  # Assign your requested colors to each medal type
  scale_fill_manual(values = c(
    "Gold" = "green",
    "Silver" = "blue",
    "Bronze" = "red"
  )) +
  # Optional: Add clear labels for readability
  labs(title = "Top 10 Countries by Medal Type (1924-2000)",
       x = "Country Code",
       y = "Total Medals",
       fill = "Medal Type")

Why Your Previous Method Didn't Work

When you used order(-maingraph2$MedalCount), you only sorted the rows of your dataset—not the underlying factor levels of the Medal column. ggplot ignores row order for categorical aesthetics like fill; it only cares about the factor's predefined level sequence.

That should give you the exact stacked order and colors you're looking for!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 15:32:58