Search code examples
vega-litevega

How to specify the order of labels in the color legend of Vega?


I have the following definition which draws lines from two groups of data: A and B. When using the "color" property in "encoding", Vega will create a legend for the colors and will display the groups in alphabetical order by default. How can I specify the that I want B to appear before A in the legend?

More generally, I want to be able to sort labels in any order, not just descending or ascending order.

See the chart here.

{
  "data": {
    "values": [
      {"x":"1", "group": "B", "value":0.2},
      {"x":"2", "group": "B", "value":0.4},
      {"x":"3", "group": "B", "value":0.3},
      {"x":"1", "group": "A", "value":0.1},
      {"x":"2", "group": "A", "value":0},
      {"x":"3", "group": "A", "value":0.2}
    ]
  },
  "mark": "line",
  "encoding": {
    "x": {"field": "x"},
    "y": {"field": "value", "type": "quantitative"},
    "color": {"field": "group"}
  }
}

Solution

  • You can add a sort to the encoding.

    enter image description here

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      
      "data": {
        "values": [
          {"x": "1", "group": "B", "value": 0.2},
          {"x": "2", "group": "B", "value": 0.4},
          {"x": "3", "group": "B", "value": 0.3},
          {"x": "1", "group": "A", "value": 0.1},
          {"x": "2", "group": "A", "value": 0},
          {"x": "3", "group": "A", "value": 0.2}
        ]
      },
      "mark": "line",
      "encoding": {
        "x": {"field": "x"},
        "y": {"field": "value", "type": "quantitative"},
        "color": {"field": "group", "sort": "descending"}
      }
    
    }
    

    You can also add a custom sort as follows:

    "sort": ["B", "A", "C"]