对于 Vega Lite,使用数据作为数组而不是 table

Use data as arrays instead of table for Vega Lite

如何在 VegaLite 中使用数组数据?

我想将数据用作数组

dates   = [1, 2, 3]
prices1 = [1, 2, 1]
prices2 = [1.5, 1, 2]

而不是 VegaLite 中传统使用的 table 数据

[
  { "date": 1, "price": 1, "symbol": 1 },
  { "date": 2, "price": 2, "symbol": 1 },
  { "date": 3, "price": 1, "symbol": 1 },

  { "date": 1, "price": 1.5, "symbol": 2 },
  { "date": 2, "price": 1,   "symbol": 2 },
  { "date": 3, "price": 2,   "symbol": 2 }
]

完整示例playground

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "Stock prices of 5 Tech Companies over Time.",
  "data": {
    "values": [
      { "date": 1, "price": 1, "symbol": 1 },
      { "date": 2, "price": 2, "symbol": 1 },
      { "date": 3, "price": 1, "symbol": 1 },

      { "date": 1, "price": 1.5, "symbol": 2 },
      { "date": 2, "price": 1,   "symbol": 2 },
      { "date": 3, "price": 2,   "symbol": 2 }
    ]
  },
  "mark": {
    "type": "line",
    "point": {
      "filled": false,
      "fill": "white"
    }
  },
  "encoding": {
    "x": {"field": "date", "type": "quantitative"},
    "y": {"field": "price", "type": "quantitative"},
    "color": {"field": "symbol", "type": "nominal"}
  }
}

您可以使用一系列数据转换来实现此目的:

  1. A Flatten transform 将数据数组转换为正常的 table 条目
  2. A Fold transform 将两个价格列转换为带有一列标签的单个价格列
  3. A Calculate transform using an appropriate Vega Expression 从您的价格标签中提取号码。

结果是这样的:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "Stock prices of 5 Tech Companies over Time.",
  "data": {
    "values": [
      {"date": [1, 2, 3], "prices1": [1, 2, 1], "prices2": [1.5, 1, 2]}
    ]
  },
  "transform": [
    {"flatten": ["date", "prices1", "prices2"]},
    {"fold": ["prices1", "prices2"], "as": ["symbol", "price"]},
    {"calculate": "slice(datum.symbol, -1)", "as": "symbol"}
  ],
  "mark": {"type": "line", "point": {"filled": false, "fill": "white"}},
  "encoding": {
    "x": {"field": "date", "type": "quantitative"},
    "y": {"field": "price", "type": "quantitative"},
    "color": {"field": "symbol", "type": "nominal"}
  }
}

要探索转换的作用,打开 Vega Editor 中的图表并使用 数据查看器 选项卡探索每个转换如何修改会很有用基础数据。