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

请求协助:为Vega-Lite多度量分组柱状图添加数据标签

为Vega-Lite分组柱状图添加数据标签

要给这个分组柱状图添加数据标签,只需把原配置里的spec从单一的bar标记改成包含bar和text的层结构即可,修改后的完整代码如下:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "url": "data/movies.json"
  },
  "repeat": {"layer": ["Worldwide Gross", "US Gross"]},
  "spec": {
    "layer": [
      {
        "mark": "bar",
        "encoding": {
          "x": {
            "field": "Major Genre",
            "type": "nominal"
          },
          "y": {
            "aggregate": "sum",
            "field": {"repeat": "layer"},
            "type": "quantitative",
            "title": "Total Gross"
          },
          "color": {"datum": {"repeat": "layer"}, "title": "Gross",
          "scale": {"range": ["#2a9d8f", "#e76f51"]}},
          "xOffset": {"datum": {"repeat": "layer"}}
        }
      },
      {
        "mark": {
          "type": "text",
          "align": "center",
          "baseline": "bottom",
          "dy": -5,
          "color": "#333"
        },
        "encoding": {
          "x": {
            "field": "Major Genre",
            "type": "nominal"
          },
          "y": {
            "aggregate": "sum",
            "field": {"repeat": "layer"},
            "type": "quantitative"
          },
          "text": {
            "aggregate": "sum",
            "field": {"repeat": "layer"},
            "type": "quantitative",
            "format": ".2s"
          },
          "xOffset": {"datum": {"repeat": "layer"}}
        }
      }
    ]
  },
  "config": {
    "mark": {"invalid": null}
  }
}

关键修改说明:

  • 把原spec中的单一bar标记替换为layer数组,同时保留柱状图和新增文本标签层
  • 文本标签的x、y、xOffset编码和柱状图完全匹配,确保标签和对应柱子精准对齐
  • text字段使用与y轴相同的sum聚合计算结果,format: ".2s"用来简化数值显示(比如把123456显示为120k)
  • 通过dy: -5把标签放在柱子上方,align: center和baseline: bottom保证标签居中对齐,color设为深灰色提升可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:35:18