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

ggplot中scale_fill_manual无法修改柱状图颜色的问题排查

问题描述

尝试使用scale_fill_manual为柱状图设置颜色,将前5个城市的柱子设为红色,剩余9个设为蓝色,但该命令无任何效果且未报错。

数据集

# A tibble: 14 × 3
   City                      Wage PPA
   <chr>                    <dbl> <dbl>
 1 Livorno                   17.0 107. 
 2 Siena                     17.6 107. 
 3 Terni                     16.7 107. 
 4 Ancona                    17.3 107. 
 5 Roma                      21.4 107. 
 6 Chieti                    23.7  89.3
 7 Teramo                    23.1  89.3
 8 Brindisi                  24.0  89.3
 9 Agrigento                 23.8  89.3
10 Caltanissetta             24.0  89.3
11 Enna                      24.2  89.3
12 Nuoro                     23.0  89.3
13 Oristano                  23.1  89.3
14 Sassari                   23.7  89.3

原代码

dataset%>%
ggplot(aes(x = reorder(City, Wage), y = Wage)) +
  geom_col() +
  coord_flip()+
  scale_fill_manual(values=c(rep("red",5), rep("blue",9)))+n  theme_classic()

错误原因与修正方案

错误点1:未映射fill属性

scale_fill_manual是用来匹配绑定到fill美学的变量的颜色规则,你代码的aes中没有指定fill字段,导致配色规则没有作用对象,自然不会生效。

错误点2:代码笔误

原代码里+n theme_classic()多了一个多余的n,这属于语法小错误,需要删除。

错误点3:排序后城市顺序与原始数据集不一致

reorder(City, Wage)会让城市按Wage升序排列,此时原始数据集的前5个城市不一定是排序后的前5个,直接用rep("red",5)会对应排序后的前5个(即工资最低的5个),如果你的需求是原始数据集的前5个城市设为红色,需要先给数据集添加分组标识。


修正后的代码(两种场景)

场景1:给排序后的前5个柱子设为红色(即工资最低的5个城市)

直接在geom_col里指定fill的颜色向量,与reorder后的城市顺序对应:

dataset %>%
  ggplot(aes(x = reorder(City, Wage), y = Wage)) +
  geom_col(fill = c(rep("red",5), rep("blue",9))) +
  coord_flip() +
  theme_classic()

场景2:给原始数据集的前5个城市(Livorno、Siena、Terni、Ancona、Roma)设为红色

先添加分组列,再映射fill并设置对应颜色:

dataset %>%
  mutate(group = ifelse(row_number() <=5, "top5", "others")) %>%
  ggplot(aes(x = reorder(City, Wage), y = Wage, fill = group)) +
  geom_col() +
  coord_flip() +
  scale_fill_manual(values = c("top5" = "red", "others" = "blue")) +
  theme_classic() +
  theme(legend.position = "none") # 可选:隐藏图例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:12:56