如何在Vega-Lite中编码基于表格的数据?

问题描述 投票:0回答:2

首先,很难用“基于表格的数据”来描述我的确切含义,因为在某种程度上vega的所有输入数据都是“table-ish”,但是这个例子应该说清楚:

大多数(如果不是全部)用于多线图的Vega-Lite examples使用的数据如,

"data": {
  "values": [
    {"id": 0, "symbol": "A", "value": 4},
    {"id": 1, "symbol": "A", "value": 2},
    {"id": 0, "symbol": "B", "value": 3},
    {"id": 1, "symbol": "B", "value": 8}
  ]
}

这是一个简单的颜色AB的线条与这样的ecoding,

"mark": "line",
"encoding": {
  "x": {"field": "id", "type": "quantitative"},
  "y": {"field": "value", "type": "quantitative"},
  "color": {"field": "symbol", "type": "nominal"}
}

但是,如果我想用这样的基于表格的数据生成相同的结果,

"data": {
  "values": [
    {"id": 0, "A": 4, "B": 3},
    {"id": 1, "A": 2, "B": 8}
  ]
}

1.如何将基于表格的数据编码为一个彩色多线图?

一个基本的编码可能是为每个字段创建折线图,并将它们叠加在一起,如this

"encoding": {
      "x": {"field": "id", "type": "quantitative"}
  },
  "layer": [
    {
      "mark": "line",
      "encoding": {
        "y": {"field": "A", "type": "quantitative"}
      }
    },
    {
      "mark": "line",
      "encoding": {
        "y": {"field": "B", "type": "quantitative"}
      }
    }
  ]

但有了这个,我不知道如何以不同的方式为线条着色或如何创建图例。

2.这种类型的输入数据是否与vega / vega-lite的设计方式不同?

encoding data-visualization vega vega-lite
2个回答
1
投票

vega-lite使用的数据通常称为“长形式”或“列式”数据。您询问的数据类型通常称为“宽格式”或“面向行”的数据。这在Altair的文档中进行了简要讨论,Altair是vega-lite的Python包装器:https://altair-viz.github.io/user_guide/data.html#long-form-vs-wide-form-data

在当前版本的Vega-Lite(v2.X)中,您唯一的选择是使用外部工具将数据源修改为面向列。这将在Vega-Lite的v3.0版本中发生变化,该版本添加了Fold transform,旨在将面向行的数据转换为图表规范中的面向列的数据。

所以,在Vega-Lite 3中,你可以像这样使用折叠变换(vega editor link):

{
  "data": {"values": [{"id": 0, "A": 4, "B": 3}, {"id": 1, "A": 2, "B": 8}]},
  "transform": [{"fold": ["A", "B"]}],
  "mark": "line",
  "encoding": {
    "x": {"field": "id", "type": "quantitative"},
    "y": {"field": "value", "type": "quantitative"},
    "color": {"field": "key", "type": "nominal"}
  }
}

enter image description here


0
投票

另一个解决方案(有点单调乏味)是使用图层并为n列创建n个图层

{
  "$schema": "https://vega.github.io/schema/vega-lite/v3.json",
  "data": {"url": "data/seattle-weather.csv", "format": {"type": "csv"}},
  "layer": [{
    "mark": {"type": "line", "color": "orange"},
    "encoding": {
      "x": {"timeUnit": "yearmonthdate", "field": "date", "type": "temporal"},
      "y": {"field": "temp_max", "type": "quantitative"}
    }
  }, {
    "mark": {"type": "line", "color": "red"},
    "encoding": {
      "x": {"timeUnit": "yearmonthdate", "field": "date", "type": "temporal"},
      "y": {"field": "temp_min", "type": "quantitative"}
    }
  }]
}

enter image description here

未来对层重复(https://github.com/vega/vega-lite/issues/1274)的支持可能使这成为更合理的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.