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

如何在ggplot中根据堆叠条形图背景填充色调整文本标签颜色

你之前配置不生效的原因是geom_text的color参数被写死为固定白色,没有和变量建立映射关系,两种可用实现方案如下:


方案1:直接映射数据集中的color变量

你已经在数据集中提前生成了对应文本颜色的color列,直接将其映射到geom_text的color审美,搭配scale_color_identity()直接使用数据中存储的颜色值即可:

library(dplyr)
library(ggplot2)
df <- mpg %>% 
  mutate(cyl = as.character(cyl)) %>% 
  group_by(model, cyl) %>% 
  summarize(hwy = mean(hwy), .groups = "keep") %>% 
  ungroup() %>% 
  group_by(model) %>% 
  mutate(hwy = round(hwy / sum(hwy), 2)) %>% 
  ungroup() %>% 
  head(11) %>% 
  mutate(color = case_when(cyl == "4" ~ "white", 
                           cyl == "6" ~ "black", 
                           cyl == "8" ~ "black"))

df %>% 
  ggplot(aes(x = model, y = hwy, fill = cyl, label = hwy)) + 
  geom_bar(stat = "identity", position = "fill") + 
  # 将color参数移入aes中,映射数据集中的color列
  geom_text(aes(color = color), position = position_stack(vjust = 0.5)) + 
  scale_fill_manual(values = c("dark blue", "light blue", "green"), 
                    name = "cyl",
                    breaks = c("4", "6", "8"),
                    labels = c("4", "6", "8")) +
  # 直接使用数据中存储的颜色值,guide="none"可隐藏额外的颜色图例
  scale_color_identity(guide = "none")

方案2:ggplot内部动态映射文本颜色

不需要提前在数据集生成color列,直接将cyl变量映射到文本颜色,手动指定颜色对应规则即可:

library(dplyr)
library(ggplot2)
df <- mpg %>% 
  mutate(cyl = as.character(cyl)) %>% 
  group_by(model, cyl) %>% 
  summarize(hwy = mean(hwy), .groups = "keep") %>% 
  ungroup() %>% 
  group_by(model) %>% 
  mutate(hwy = round(hwy / sum(hwy), 2)) %>% 
  ungroup() %>% 
  head(11)

df %>% 
  ggplot(aes(x = model, y = hwy, fill = cyl, label = hwy)) + 
  geom_bar(stat = "identity", position = "fill") + 
  # 将color映射到cyl变量
  geom_text(aes(color = cyl), position = position_stack(vjust = 0.5)) + 
  scale_fill_manual(values = c("dark blue", "light blue", "green"), 
                    name = "cyl",
                    breaks = c("4", "6", "8"),
                    labels = c("4", "6", "8")) +
  # 手动指定每个cyl值对应的文本颜色,和fill共用同一个图例
  scale_color_manual(values = c("4" = "white", "6" = "black", "8" = "black"),
                     name = "cyl")

实现效果示意:
堆叠条形图文本颜色适配效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 11:39:03