Search code examples
jsonchartsvisualizationvega-lite

encoding based on condition, somehow like an else if


this is my vega-lite spec

{
  
  "data": {
    "values": [
      {"group": "I", "groupSort": 1, "segment": "A", "val": 1},
      {"group": "II", "groupSort": 2, "segment": "B", "val": -3},
      {"group": "III", "groupSort": 3, "segment": "A", "val": 2},
      {"group": "IV", "groupSort": 4, "segment": "B", "val": 3},
      {"group": "V", "groupSort": 5, "segment": "E", "val": -2}
    ]
  },
  "mark": {
    "type": "text", "size": 20,
    "text": "➟" 
    },
  "encoding":{
    "y": {
      "field": "group", "type": "nominal"
    },
    "color": {
                  "condition": {"test": "datum['val'] < 0", "value": "red"},
              "value": "green"},
     "angle": {
                  "condition": {"test": "datum['val'] < 0", "value": 90},
              "value": -45}     
  }
}

What I want is

  • a red arrow if val is < 0
  • a yellow arrow if val <= 0 && <3
  • a green arrow if val >= 3

But I have no idea about the syntax :-( Is this kind of logic possible in the encoding at all or do I have to move this to the transform?

Thanks, Tom


Solution

  • Add your tests to an array as follows.

    enter image description here

    {
      "data": {
        "values": [
          {"group": "I", "groupSort": 1, "segment": "A", "val": 1},
          {"group": "II", "groupSort": 2, "segment": "B", "val": -3},
          {"group": "III", "groupSort": 3, "segment": "A", "val": 2},
          {"group": "IV", "groupSort": 4, "segment": "B", "val": 3},
          {"group": "V", "groupSort": 5, "segment": "E", "val": -2}
        ]
      },
      "mark": {"type": "text", "size": 20, "text": "➟"},
      "encoding": {
        "y": {"field": "group", "type": "nominal"},
        "color": {
          "condition": [
            {"test": "datum['val'] < 0", "value": "red"},
            {"test": "datum['val'] >= 0 && datum['val'] < 3  ", "value": "yellow"},
            {"test": "datum['val'] >= 3  ", "value": "green"}
          ]
        },
        "angle": {
          "condition": {"test": "datum['val'] < 0", "value": 90},
          "value": -45
        }
      }
    }