首页 > 解决方案 > 使用数据作为数组而不是 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 }
]

操场的完整示例

{
  "$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"}
  }
}

标签: vega-lite

解决方案


您可以使用一系列数据转换来实现这一点:

  1. 将数据数组转换为普通表条目的扁平化转换
  2. 将两个价格列转换为带有标签列的单个价格列的折叠转换
  3. 使用适当的Vega 表达式进行计算转换,以从您的价格标签中提取数字。

结果是这样的:

{
  "$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 编辑器中打开图表并使用数据查看器选项卡来探索每个转换如何修改基础数据会很有用。


推荐阅读