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

无需新增color列,在ggplot2双geom_bar图中配置scale_fill_manual性别配色

解决ggplot2中按Type指定自定义填充色的问题

问题描述

需要为pop_gen_df数据集中Type列的males和females分别设置填充色#149ECE和#FC921F,尝试scale_fill_manual(values=c("#FC921F","#149ECE", Type))时出现Error in is_missing(values) : object 'Type' not found错误,要求无需新增颜色列实现需求。

错误原因

错误地将Type变量传入scale_fill_manual的values参数中,该参数需要的是与离散类别对应的颜色向量,而非数据列。

修正后的完整代码

library(tidyverse)
library(plotly)

# 加载数据集
pop_gen_df <- structure(list(age_group = c("<  5 years", "5 - 14", "15  -  24", 
"25  -  34", "35  -  44", "45  -  54", "55  -  64", "65  -  74", 
"75  -  84", "85 +", "<  5 years", "5 - 14", "15  -  24", "25  -  34", 
"35  -  44", "45  -  54", "55  -  64", "65  -  74", "75  -  84", 
"85 +"), Type = c("males", "males", "males", "males", "males", 
"males", "males", "males", "males", "males", "females", "females", 
"females", "females", "females", "females", "females", "females", 
"females", "females"), Value = c(-6, -13, -13, -15, -17, -15, 
-11, -6, -3, -1, 6, 12, 12, 14, 16, 15, 12, 7, 4, 2)), row.names = c(NA, 
-20L), class = c("tbl_df", "tbl", "data.frame"))

# 绘图代码
gg_pop_hisp = ggplot(pop_gen_df, aes(x = age_group, y = Value, fill = Type)) +
  geom_bar(data = subset(pop_gen_df, Type == "females"), stat = "identity") + 
  geom_bar(data = subset(pop_gen_df, Type == "males"), stat = "identity") + 
  scale_y_continuous(labels = function(z) paste0(abs(z), "%")) +
  # 用命名向量绑定Type与对应颜色
  scale_fill_manual(
    name = "Gender",
    labels = c("Females", "Males"),
    values = c(females = "#FC921F", males = "#149ECE")
  ) +
  ggtitle("HISPANIC POPULATION BY GENDER AND AGE GROUP") +
  labs(x = "AGE GROUPS", y = "PERCENTAGE POPULATION") +
  theme_classic() +
  coord_flip()

# 交互式可视化
ggplotly(gg_pop_hisp)

关键修改说明

  1. 自定义颜色映射:使用scale_fill_manual并传入命名向量values = c(females = "#FC921F", males = "#149ECE"),直接将Type的每个类别与指定颜色绑定,无需新增数据列。
  2. 修正标签错误:调整了labs中x、y轴的标签对应关系,适配coord_flip()后的轴显示。
  3. 统一数据集名称:将原代码中不一致的数据集名称统一为pop_gen_df。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 07:36:32