简体   繁体   English

Vega-Lite:添加不基于字段值/自动颜色/自动形状的自定义图例

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

I'm looking for a way to output custom legends for multi-field data.我正在寻找一种方法来 output 自定义多字段数据的图例。 Ideally, I'd like to statically color-code all the fields I may have (in total there might be about 20), and output legends per color and arbitrary text, or at least a field name.理想情况下,我想对我可能拥有的所有字段(总共可能有大约 20 个)以及每种颜色和任意文本的 output 图例或至少一个字段名称进行静态颜色编码。

In the example below, I'd like a legend to show " blue stroke Series 1 red stroke Series 2".在下面的示例中,我想要一个图例来显示“ blue stroke系列 1 red stroke系列 2”。

I'd be happy to show what I have at the moment, but I have tried placing "legend" seemingly everywhere it may fit, and it doesn't do anything.我很乐意展示我目前拥有的东西,但我已经尝试将“图例”放置在它可能适合的任何地方,但它并没有做任何事情。

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

Legends in Vega-Lite are created from encodings, so if you want a legend to be shown you need to construct an appropriate encoding. Vega-Lite 中的图例是根据编码创建的,因此如果您想要显示图例,您需要构建适当的编码。 For layered charts, one way to do this is using a datum encoding for each layer, and then you can construct a custom color scale mapping these encodings to the desired color.对于分层图表,一种方法是为每一层使用datum编码,然后您可以构建自定义色标,将这些编码映射到所需的颜色。 For example ( 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"}
      }
    }
  ]
}

在此处输入图像描述

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

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