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

求助:如何使ggplot图表中的字母颜色与柱状图颜色一致?

解决方法

要让图表中字母颜色和柱状图填充色一致,只需对代码做两处修改:

  1. 给geom_text的映射参数(aes)添加colour = Specie,让文字颜色和物种(Specie)关联
  2. 同步添加scale_colour_manual,使用和填充色相同的颜色值,确保颜色匹配

修改后的完整代码:

ggplot(df, aes(x=reorder(Genotype,-Phy), y=Phy, fill=Specie, colour=Specie)) + 
  geom_bar(stat="identity", position=position_dodge(), color="black") + 
  geom_errorbar(aes(ymin=Phy, ymax=Phy+sd), width=0.5,position=position_dodge(0.9)) + 
  geom_text(aes(y = Phy+sd+0.02, label = tk, colour = Specie),  # 新增colour映射
            position = position_dodge(width = 0.9),
            vjust=0.3,hjust=0.5, size = 3.5, angle=90) +
  theme(panel.background = element_rect(colour = "black",fill = "white"),
        panel.grid.major = element_line(size = 0.5, linetype = 'solid',colour = "lightgray"),
        axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, colour = "black", face = "bold"),
        axis.text.y =element_text(colour="black", size = "10", face = "bold"),
        legend.position=c(0.915, 0.85),legend.background = element_rect(fill='transparent'),
        legend.key.size = unit(4, 'mm'),
        legend.text = element_text(size = 9, face="italic", colour = "black")) + 
  scale_fill_manual(values=c('#e9002d', '#ffaa00', '#00b000'))+
  scale_colour_manual(values=c('#e9002d', '#ffaa00', '#00b000'))+  # 新增颜色刻度,和填充色一致
  expand_limits(y=0.68)+
  scale_y_continuous(breaks = seq(0, 1, 0.1)) + labs(title="",y=y, x="") 

关键说明:

  • geom_text里的colour = Specie会让每个物种对应的文字自动匹配该物种的颜色
  • scale_colour_manual必须和scale_fill_manual使用完全相同的颜色值,这样文字颜色才会和柱状图填充色精准对应
  • 原代码中geom_bar的color="black"是设置柱状图的边框颜色,不影响填充色和文字颜色的映射逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 06:25:09