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

在Vega-Lite堆叠柱状图顶部添加总计标签的技术求助

解决堆叠柱状图顶部仅显示单个总计标签的问题

要实现只在堆叠柱状图顶部显示总计标签,你需要单独新增一个图层处理总和文本,而非在每个堆叠层中添加标签。具体修改如下:

修改步骤

  1. 移除原有堆叠图层中的文本标记,仅保留柱状图的bar标记。
  2. 添加新图层,使用text标记,基于聚合后的总和数据渲染顶部标签。

修改后的完整代码

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "values": [
      {"category": "A", "group": "x", "value": 10},
      {"category": "A", "group": "y", "value": 20},
      {"category": "B", "group": "x", "value": 15},
      {"category": "B", "group": "y", "value": 25},
      {"category": "C", "group": "x", "value": 8},
      {"category": "C", "group": "y", "value": 12}
    ]
  },
  "layer": [
    // 堆叠柱状图图层
    {
      "mark": "bar",
      "encoding": {
        "x": {"field": "category", "type": "nominal"},
        "y": {"field": "value", "type": "quantitative"},
        "color": {"field": "group", "type": "nominal"}
      },
      "transform": [{"stack": "value"}]
    },
    // 顶部总计标签图层
    {
      "mark": {"type": "text", "dy": -5, "align": "center"},
      "encoding": {
        "x": {"field": "category", "type": "nominal"},
        "y": {"aggregate": "sum", "field": "value", "type": "quantitative"},
        "text": {"aggregate": "sum", "field": "value", "type": "quantitative"}
      }
    }
  ]
}

关键说明

  • 新增的文本图层通过aggregate: 'sum'计算每个分类的总数值,确保仅显示一个总和标签。
  • dy: -5将标签定位在柱子顶部上方,避免与柱子重叠。
  • 文本图层放在图层数组末尾,保证标签显示在柱状图上层。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 18:33:24