如何在Vega Lite中为单个或多个系列图表添加图例?

时间:2018-02-03 05:04:06

标签: vega vega-lite

如何在Vega的基本图表中添加图例?

我在网络应用中使用Vega,我希望我的所有图表都包含一个图例,即使它只是一个系列。

,即在Google表格中,它看起来像enter image description here

1 个答案:

答案 0 :(得分:0)

由于Datum还没有实现,我添加了一个额外的图层作为解决方法(这也适用于多系列图表,方法是在规则的data.values中添加其他值。)

        {
          "mark": {
            "type": "rule"
          },
          "data": {
            "values": [
              {
                "color": "Total Units"
              }
            ]
          },
          "encoding": {
            "color": {
              "field": "color", 
              // If you want to update the color of the legend...
              "scale": {"range": ["blue", "#000"]}, 
              "sort": false,
              "type": "nominal",
              "legend": { "title": "" }
            } 
          }
        }

对于那些想要在VegaLite编辑器中查看示例的人https://vega.github.io/editor/#/

{
  "layer": [
    {
      "mark": "bar",
      "data": {
        "values": [
          {
            "goal": 25,
            "project": "a",
            "score": 25
          },
          {
            "goal": 47,
            "project": "b",
            "score": 57
          },
          {
            "goal": 30,
            "project": "c",
            "score": 23
          },
          {
            "goal": 27,
            "project": "d",
            "score": 19
          }
        ]
      },
      "encoding": {
        "x": {
          "type": "nominal",
          "field": "project"
        },
        "y": {
          "type": "quantitative",
          "field": "score"
        }
      },
      "height": 300,
      "width": 400
    },
    {
      "mark": {
        "type": "rule"
      },
      "data": {
        "values": [
          {
            "color": "Goal"
          }
        ]
      },
      "encoding": {
        "color": {
          "field": "color", 
          "sort": false,
          "type": "nominal",
          "legend": { "title": "" }
        } 
      }
    }
  ]
}