Klaus Eckelt
Klaus Eckelt

Reputation: 685

Sort bars of Stacked Bar Chart

For a Stacked Bar Chart, can you sort the bars by the size of one of the segments?

E.g., take this Stacked Bar Chart from the examples (Open Editor):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {"url": "data/barley.json"},
  "mark": "bar",
  "encoding": {
    "x": {"aggregate": "sum", "field": "yield"},
    "y": {"field": "variety"},
    "color": {"field": "site"}
  }
}

barley yield per site

Now I would like to sort the y-axis based on the yield in Crookston. Is that possible?

Upvotes: 1

Views: 493

Answers (1)

jakevdp
jakevdp

Reputation: 86443

Sorting by the total of another field is relatively easy; you can do so with the "sort" entry of the desired encoding (sort docs):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {"url": "data/barley.json"},
  "mark": "bar",
  "encoding": {
    "x": {"aggregate": "sum", "field": "yield"},
    "y": {"field": "variety", "sort": {"op": "sum", "field": "yield"}},
    "color": {"field": "site"}
  }
}

enter image description here

If you want to sort just by the value when site == "Crookston", you can do so by first applying a calculate transform to select just that value:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {"url": "data/barley.json"},
  "transform": [
    {
      "calculate": "datum.site == 'Crookston' ? datum.yield : 0",
      "as": "crookston"
    }
  ],
  "mark": "bar",
  "encoding": {
    "x": {"aggregate": "sum", "field": "yield"},
    "y": {"field": "variety", "sort": {"op": "sum", "field": "crookston"}},
    "color": {"field": "site"}
  }
}

enter image description here

Upvotes: 1

Related Questions