在 Vega-Lite 中创建自定义条形图

Creating custom bar chart in Vega-Lite

我是 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"
      }
   }
}

这是它的作用

我需要做什么才能获得我想要的输出?这里有一个关于主题 的问题,但它是在 python altair 中完成的,我不想这样做。我想仅使用 Vega-Lite.

来生成它

提前致谢。

您可以使用 bin transform followed by a window transform to generate the fields required to create this kind of chart. For example (open in editor):

{
  "data": {"url": "data/cars.json"},
  "transform": [
    {"bin": {"maxbins": 50}, "field": "Horsepower", "as": "Horsepower"},
    {"window": [{"op": "count", "as": "index"}], "groupby": ["Horsepower"]}
  ],
  "mark": {
    "type": "rect",
    "tooltip": true,
    "strokeWidth": 0.3,
    "stroke": "white"
  },
  "encoding": {
    "x": {"field": "Horsepower", "type": "quantitative", "bin": "binned"},
    "x2": {"field": "Horsepower_end"},
    "y": {
      "field": "index",
      "type": "ordinal",
      "scale": {"reverse": true},
      "title": "count"
    }
  },
  "width": 400,
  "height": 300
}