jsonvisualizationvegavega-lite-apivega-embed

How to sort order of stacked bar


I am trying to create a stack bar chart in Vegalite. my requirement is specific i want to stack the bar in the same order as in legend (legend are in order as data ) , i want to stack bar from bottom to top .

in the above chart legend are in same order as my data ["first","Second","third"] but the bar stacking not in same order i.e worng order ["Second","first","third"] but i want ["first","Second","third"] order from top to bottom i.e lower one ->"first","mid"->"Second",top->"third" follow legend order how i can achieve this in any way?

editor link


Solution

  • Add a scale and order:

    enter image description here

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      "data": {
        "values": [
          {"category": "A", "group": "first", "value": 1, "order":1},
          {"category": "A", "group": "Second", "value": 3, "order":2},
          {"category": "A", "group": "third", "value": 5, "order":3},
          {"category": "B", "group": "first", "value": 0.7, "order":1},
          {"category": "B", "group": "Second", "value": 0.2, "order":2},
          {"category": "B", "group": "third", "value": 1.1, "order":3},
          {"category": "C", "group": "first", "value": 5, "order":1},
          {"category": "C", "group": "Second", "value": 4, "order":2},
          {"category": "C", "group": "third", "value": 9, "order":3}
        ]
      },
      "mark": {"type": "bar", "tooltip": true},
      "encoding": {
        "order": {"field": "order", "sort": "descending"} ,
        "x": {"field": "category"},
        "y": {"field": "value", "type": "quantitative"},
        "color": {
          "field": "group",
          "type": "nominal", 
          "scale": {"domain": ["first", "Second", "third"]}
        }
      }
    }