Vega-Lite:添加不基于字段 value/auto color/auto 形状的自定义图例

Vega-Lite: Adding custom legends not based on the field value/auto color/auto shape

我正在寻找一种为多字段数据输出自定义图例的方法。理想情况下,我想对我可能拥有的所有字段进行静态颜色编码(总共可能有大约 20 个),并输出每种颜色的图例和任意文本,或者至少输出一个字段名称。

在下面的示例中,我想要一个图例来显示“blue stroke 系列 1 red stroke 系列 2”。

我很乐意展示我目前拥有的东西,但我已经尝试将“图例”放置在任何它可能适合的地方,但它没有任何作用。

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "values": [
      {"x": 1, "y": 10},
      {"x": 2, "y": 7},
      {"x2": 1, "y2": 11},
      {"x2": 2, "y2": 12}
    ]
  },
  "encoding": {"x": {"type": "quantitative"}, 
               "y": {"type": "quantitative"}},
  "layer": [
    {
      "layer": [
        {
          "mark": "line",
          "encoding": {
            "x": {"field": "x"}, 
            "y": {"field": "y"},
            "color": {"value": "blue"}
            
            }
        },
        {
          "mark": "line",
          "encoding": {
            "x": {"field": "x2"},
            "y": {"field": "y2"},
            "color": {"value": "red"}
          }
        }
      ]
    }
  ]
}

Vega-Lite 中的图例是根据编码创建的,因此如果您想要显示图例,则需要构建适当的编码。对于分层图表,一种方法是对每一层使用 datum 编码,然后您可以构建自定义色标,将这些编码映射到所需的颜色。例如 (open in editor):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "values": [
      {"x": 1, "y": 10},
      {"x": 2, "y": 7},
      {"x2": 1, "y2": 11},
      {"x2": 2, "y2": 12}
    ]
  },
  "encoding": {
    "x": {"type": "quantitative"},
    "y": {"type": "quantitative"},
    "color": {
      "type": "nominal",
      "scale": {"domain": ["Series1", "Series2"], "range": ["blue", "red"]}
    }
  },
  "layer": [
    {
      "mark": "line",
      "encoding": {
        "x": {"field": "x"},
        "y": {"field": "y"},
        "color": {"datum": "Series1"}
      }
    },
    {
      "mark": "line",
      "encoding": {
        "x": {"field": "x2"},
        "y": {"field": "y2"},
        "color": {"datum": "Series2"}
      }
    }
  ]
}