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

如何在Vega-Lite中实现类Unsub直方图的自定义柱状图

问题说明

我是Vega-Lite的新手,目前想要复刻如下图所示的图表效果:
预期实现的图表
以下是我编写的代码,运行后无法得到预期效果:

{
   "$schema":"https://vega.github.io/schema/vega-lite/v5.json",
   "width":800,
   "height":600,
   "autosize":{
      "type":"fit",
      "contains":"padding"
   },
   "data":{
      "url":"data/cars.json"
   },
   "mark":{
      "type":"rect",
      "tooltip":true,
      "strokeWidth":0.1,
      "stroke":"white"
   },
   "encoding":{
      "x":{
         "field":"Horsepower",
         "type":"quantitative",
         "bin":{
            "maxbins":100
         },
         "axis":{
            "labelAngle":0
         }
      },
      "y":{
         "aggregate":"count",
         "field":"Horsepower",
         "type":"quantitative"
      }
   }
}

当前代码实际输出的效果如下:
当前代码输出效果

解决方案

你当前代码用了count聚合作为y轴取值,输出的是普通统计直方图,和预期的每个小方块代表单个数据点的瓦片直方图效果不符,按以下要求修改即可:

  1. 新增transform配置,对每个马力分箱下的所有数据生成独立行号,作为y轴的定位依据
  2. 把y轴的聚合计数配置替换为生成的行号字段,设置为序数类型、隐藏y轴
  3. 可选:如果需要自定义配色,可以在encoding中新增color配置绑定对应字段

完整可运行代码如下:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "width": 800,
  "height": 600,
  "autosize": {
    "type": "fit",
    "contains": "padding"
  },
  "data": {
    "url": "data/cars.json"
  },
  "transform": [
    {
      "window": [{"op": "row_number", "as": "row_num"}],
      "groupby": ["bin_Horsepower", "bin_Horsepower_end"]
    }
  ],
  "mark": {
    "type": "rect",
    "tooltip": true,
    "strokeWidth": 0.1,
    "stroke": "white"
  },
  "encoding": {
    "x": {
      "field": "Horsepower",
      "type": "quantitative",
      "bin": {"maxbins": 100},
      "axis": {"labelAngle": 0}
    },
    "y": {
      "field": "row_num",
      "type": "ordinal",
      "axis": null
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 18:54:02