使用JSON和Vega-lite在散点图上绘制多个点

时间:2019-11-30 02:12:12

标签: javascript json vega vega-lite

我正在尝试使用我的大学和Vega-lite可视化库提供的Web服务API端点创建散点图。目标是使用以下方法在x轴上绘制一天中的小时数,并在y轴上绘制实例数。

    {
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "A scatterplot showing horsepower and miles per gallons for various cars.",
  "data": {"url": "https://zagster-service.herokuapp.com/rides/count/per_hour"},
  "mark": "point",
  "encoding": {
    "x": {"field": "0", "type": "quantitative"},
    "y": {"field": "1", "type": "quantitative"}
  }
}

我尝试遵循网上找到的几个示例,但是只能使用上面的代码弄清楚如何一次绘制一个点,或者手动在图形上输入每个点,但是手动操作不是我的选择目的。我的JSON文件如下所示,其中一天中的小时数由0-23表示,每个实例的计数就在其旁边。

{"0":429,"1":231,"2":130,"3":85,"4":42,"5":1,"7":1,"8":17,"9":16,"10":795,"11":425,"12":921,"13":846,"14":1795,"15":1789,"16":2119,"17":1630,"18":1942,"19":1637,"20":1636,"21":1054,"22":843,"23":710}

一段时间以来,我一直在试图找出答案,需要一些帮助,朝着正确的方向前进

1 个答案:

答案 0 :(得分:4)

vega-lite中的数据应指定为记录列表;例如而不是

{"0":429,"1":231,"2":130}

应该是

[{"x": "0", "y": 429}, {"x": "1", "y": 231}, {"x": "2", "y": 130}]

如果无法修改数据源,则可以使用fold transform重塑数据。看起来像这样(view in vega editor):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "A scatterplot showing horsepower and miles per gallons for various cars.",
  "data": {"url": "https://zagster-service.herokuapp.com/rides/count/per_hour"},
  "transform": [
    {
      "fold": ["0", "1", "2", "3", "4", "5", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"],
      "as": ["x", "y"]
    }
  ],
  "mark": "point",
  "encoding": {
    "x": {"field": "x", "type": "quantitative"},
    "y": {"field": "y", "type": "quantitative"}
  }
}

enter image description here

不幸的是,如果不明确列出要折叠的所有条目,就无法折叠这样的数据。