簡體   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