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

如何仅修改堆叠柱状图顶部单个堆叠条的字体颜色

堆叠柱状图示例

仅修改堆叠柱状图最上方堆叠条字体颜色的实现方案

以下是两种主流开发场景的实现方法:

Python Matplotlib 实现

核心逻辑是单独处理最上层堆叠对应的标签对象,不用修改其他层配置:

import matplotlib.pyplot as plt
import numpy as np

# 示例数据
categories = ['类别1', '类别2', '类别3', '类别4']
layer1 = [10, 22, 18, 25]
layer2 = [15, 12, 20, 17]
top_layer = [7, 9, 5, 11] # 最上层堆叠数据

x = np.arange(len(categories))
bar_width = 0.6

# 绘制各层堆叠柱
bar1 = plt.bar(x, layer1, bar_width, label='第一层')
bar2 = plt.bar(x, layer2, bar_width, bottom=layer1, label='第二层')
bar_top = plt.bar(x, top_layer, bar_width, bottom=np.array(layer1)+np.array(layer2), label='最上层')

# 给下层添加默认颜色标签
plt.bar_label(bar1, label_type='center')
plt.bar_label(bar2, label_type='center')
# 给最上层单独设置字体颜色,比如红色
plt.bar_label(bar_top, label_type='center', color='red')

plt.xticks(x, categories)
plt.legend()
plt.show()

如果已经统一渲染了所有标签再修改,可以直接索引最后一层的文本元素修改:

# 总共有N个类别时,最后N个文本就是最上层的标签
for text in plt.gca().texts[-len(categories):]:
    text.set_color('red')

前端ECharts实现

只需要在最上层的series配置中单独指定label的颜色,其他系列保持原有配置即可:

const option = {
  xAxis: {
    type: 'category',
    data: ['类别1', '类别2', '类别3', '类别4']
  },
  yAxis: { type: 'value' },
  series: [
    {
      name: '第一层',
      type: 'bar',
      stack: 'total',
      label: { show: true, position: 'inside' },
      data: [10, 22, 18, 25]
    },
    {
      name: '第二层',
      type: 'bar',
      stack: 'total',
      label: { show: true, position: 'inside' },
      data: [15, 12, 20, 17]
    },
    {
      name: '最上层',
      type: 'bar',
      stack: 'total',
      // 仅修改当前最上层标签颜色
      label: { show: true, position: 'inside', color: 'red' },
      data: [7, 9, 5, 11]
    }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:12:00