Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "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"]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading