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

如何使用Vega-Lite高亮柱状图中的指定柱子

Vega-Lite 柱状图指定分类高亮实现方案

你只需在原有配置的基础上调整柱状图的颜色编码规则即可实现需求,具体修改逻辑:

  • 移除第一个图层mark配置中硬编码的灰色属性"color": "#ddd"
  • 给该图层新增color编码配置,通过test条件匹配需要高亮的两个影片分类,匹配成功返回指定红色,其余分类返回指定灰色

修改后的完整配置代码如下:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "width": 200,
  "height": {"step": 16},
  "data": {"url": "data/movies.json"},
  "encoding": {
    "y": {
      "field": "Major Genre",
      "type": "nominal",
      "axis": null
    }
  },
  "layer": [{
    "mark": {"type": "bar"},
    "encoding": {
      "x": {
        "aggregate": "mean",
        "field": "IMDB Rating",
        "scale": {"domain": [0, 10]},
        "title": "Mean IMDB Ratings"
      },
      "color": {
        "condition": {
          "test": "datum['Major Genre'] === 'Documentary' || datum['Major Genre'] === 'Drama'",
          "value": "#dd2525"
        },
        "value": "#4682b4"
      }
    }
  }, {
    "mark": {"type": "text", "align": "left", "x": 5},
    "encoding": {
      "text": {"field": "Major Genre"},
      "detail": {"aggregate": "count"}
    }
  }]
}

配置说明:test属性支持写入标准JS表达式,其中datum代表当前行的数据对象,你可以自行修改判断规则匹配其他需要高亮的分类。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 02:33:02