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

如何在R的ggplot中根据数据框颜色列设置堆叠条形图填充色

解决ggplot堆叠条形图无法应用数据框指定颜色的问题

问题根源

你之前的代码存在两个核心问题:

  1. 错误地将颜色映射到colour参数(这控制的是条形边框颜色),但堆叠条形图的填充色需要通过fill参数设置
  2. scale_color_identity()仅对colour参数生效,无法影响填充区域的颜色,且你同时设置了color="black",直接覆盖了colour=col的映射

修正方案

方案1:直接使用scale_fill_identity()

将填充色直接绑定到数据框的col列,让ggplot识别列中的颜色值:

ggplot(producer_countries, aes(x=year, y=total_value)) +     
  geom_bar(
    aes(fill=col, group=reorder(Country, total_value)), 
    position="stack", stat="identity", color = "black"
  )+
  scale_fill_identity(guide = "legend", labels = unique(producer_countries$Country)) +
  xlab("Year") +
  ylab("Quantity") +
  labs(fill = "Country")
  • group=reorder(Country, total_value)保证国家按total_value排序堆叠
  • guide = "legend"和labels参数让图例显示国家名称而非颜色值

方案2:创建颜色映射表(更稳妥)

先提取每个国家对应的唯一颜色,再手动绑定填充色,避免图例混乱:

# 生成国家-颜色的唯一映射
country_color_map <- unique(producer_countries[, c("Country", "col")])
country_color_map <- setNames(country_color_map$col, country_color_map$Country)

# 绘图
ggplot(producer_countries, aes(x=year, y=total_value)) +     
  geom_bar(
    aes(fill=reorder(Country, total_value)), 
    position="stack", stat="identity", color = "black"
  )+
  scale_fill_manual(values = country_color_map) +
  xlab("Year") +
  ylab("Quantity")

这种方式逻辑更清晰,图例直接显示国家名称,适合后续维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:10:33