繁体   English   中英

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

[英]How to encode table based data in Vega-Lite?

首先,很难描述我所说的“基于表的数据”的确切含义,因为从某种意义上来说,vega的所有输入数据都是“ table-ish”的,但此示例应清楚说明:

大多数(如果不是全部)用于多折线图的Vega-Lite 示例都使用诸如

"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的线着色,

"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.如何将基于表格的数据编码为一张彩色的多折线图?

基本的编码方式是为每个字段创建折线图,然后像这样将它们彼此叠加,

"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的设计方式?

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变换 ,该变换旨在在图表规范中将面向行的数据转换为面向列的数据。

因此,在Vega-Lite 3中,您可以像这样使用fold转换( vega编辑器链接 ):

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

在此处输入图片说明

另一个解决方案(有点乏味)是使用图层并为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"}
    }
  }]
}

在此处输入图片说明

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM