簡體   English   中英

如何在 vega-lite 中定義重復和圖層 api

[英]How to define repeat and layer in vega-lite api

我有一個看起來像這樣的數據:

student_name,d,e
student1,0.1,0.7
student2,0.2,0.3
student3,0.3,0.4
student4,0.25,0.2
student5,0.4,0.15
student6,0.6,0.2
student7,0.15,0.5
student8,0.7,0.13
student9,0.56,0.22
student10,0.35,0.2

我想用vega-lite-api可視化這些數據,這樣 X 軸就會有學生,並且de列各有兩個折線圖。 我試過這樣的事情

vl
  .markLine() 
  .encode(
    vl.x().fieldN('student_name').sort('y'), 
    vl.y().fieldQ('d'),
  );

這正確地顯示了 y 軸上的d列值與 x 軸上的學生:

在此處輸入圖像描述

但是,我無法猜測我如何在 y 軸上也有列e值。 我想我需要重復和分層,像這樣

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "url": "data/movies.json"
  },
  "repeat": {
    "layer": ["US Gross", "Worldwide Gross"]
  },
  "spec": {
    "mark": "line",
    "encoding": {
      "x": {
        "bin": true,
        "field": "IMDB Rating",
        "type": "quantitative"
      },
      "y": {
        "aggregate": "mean",
        "field": {"repeat": "layer"},
        "type": "quantitative",
        "title": "Mean of US and Worldwide Gross"
      },
      "color": {
        "datum": {"repeat": "layer"},
        "type": "nominal"
      }
    }
  }
}

輸出:

在此處輸入圖像描述

但我無法猜測如何將上述 vega-lite 語法中的repeatlayer翻譯成 vega-lite-api 調用。

根據文檔,您可以使用vl.repeatvl.layer方法來構建repeatlayer對象。

然后,您可以使用vl.encode()返回的spec.repeat方法和y.field方法將它們插入到您的規范中。

使用您的示例,以下 JS 代碼

vl
  .markLine()
  .encode(
    vl.x().fieldN('student_name').sort('y'), 
    vl.y().field(vl.repeat('layer')),
  ).repeat(
    vl.layer(["d", "e"])  
  )

將 output 這個 JSON:

{
   "$schema":"https://vega.github.io/schema/vega-lite/v4.json",
   "repeat":{
      "layer":[
         "d",
         "e"
      ]
   },
   "spec":{
      "mark":{
         "type":"line"
      },
      "encoding":{
         "x":{
            "field":"student_name",
            "type":"nominal",
            "sort":"y"
         },
         "y":{
            "field":{
               "repeat":"layer"
            }
         }
      }
   }
}

此筆記本將讓您試驗此代碼的實時版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM