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

如何为Vega-Lite双Y轴柱状图添加自定义图例?

为Vega-Lite双Y轴柱状图添加双项图例的解决方案

我在编写Vega-Lite双Y轴柱状图代码时,想要添加包含两个项的图例,但尝试两种方案都出现问题:

  • 方案1:添加"color": {"field": "cost", "type": "quantitative"}后生成了渐变图例,不符合需求;
  • 方案2:图例类型正确,但图表显示异常。

修正后的代码

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "width": "container",
  "height": 550,
  "data": {
    "values": [
      {"model": "Audi", "score": 150, "cost": 4500},
      {"model": "Mercedes", "score": 75, "cost": 6000},
      {"model": "BMW", "score": 115, "cost": 5000}
    ]
  },
  "encoding": {
    "x": {"field": "model", "type": "nominal", "axis": {"labelAngle": 45, "title": "Model"}},
    "color": {
      "type": "nominal",
      "scale": {
        "domain": ["Score", "Cost"],
        "range": ["steelblue", "orange"]
      },
      "legend": {"title": "Metrics"}
    }
  },
  "layer": [
    {
      "mark": {"type": "bar", "width":{"band": 0.75}},
      "encoding": {
        "y": {"field": "score", "type": "quantitative", "axis": {"title": "Score"}, "scale":{"rangeMax":-100}},
        "xOffset":{"value": 0},
        "color": {"value": "steelblue"}
      }
    },
    {
      "mark": {"type": "bar", "width":{"band": 0.4}},
      "encoding": {
        "y": {"field": "cost", "type": "quantitative", "axis": {"title": "Cost", "orient": "right", "format": "$.0f"}},
        "xOffset":{"value": 0},
        "color": {"value": "orange"}
      }
    }
  ],
  "resolve": {
    "scale": {
      "y": "independent"
    }
  }
}

关键修改说明

  1. 定义离散颜色比例尺:在顶层encoding中配置color的离散映射规则,指定图例的两个分类项及对应颜色,确保图例为离散样式;
  2. 图层绑定对应颜色:在每个图层的encoding中通过固定值绑定颜色,让柱状图元素与图例项关联;
  3. 统一颜色控制逻辑:移除mark中硬编码的color属性,由encoding统一管理颜色映射,保证图例与图表元素的一致性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 14:22:21