简体   繁体   中英

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. 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.

In the example below, I'd like a legend to show " blue stroke Series 1 red stroke Series 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. 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. 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"}
      }
    }
  ]
}

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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