将数据用作Vega Lite的数组而不是表

时间:2019-12-24 10:31:13

标签: vega-lite

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

我想将数据用作数组

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

代替了VegaLite中传统使用的表数据

[
  { "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 个答案:

答案 0 :(得分:1)

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

  1. 一个Flatten transform,可将数据数组转换为普通表条目
  2. Fold transform,用于将两个价格列转换为带有标签列的单个价格列
  3. Calculate transform使用适当的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"}
  }
}

enter image description here

要探究转换的作用,在Vega Editor中打开图表并使用 Data Viewer 标签来探究每个转换如何修改基础数据会很有用。 / p>