Search code examples
javascriptchartsvega-litevega

Vega-lite: Change order of stacks in a stacked bar chart and ignore negative value


This is the chart I am trying to follow for my work

Vega editor

enter image description here

How could I change the order of the 'Measure' to keep 'Measure 1' at the top only by ignoring that it is a negative value? I still want to show the '-' sign in the text but I want the bar to go to the top.

For David: One of the bars are in such a way where the top blue bar can be negative but should always be on the top

: enter image description here


Solution

  • Like this? If so, you need a sort.

    enter image description here

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      "data": {
        "values": [
          {"Value": 0.321, "Date": "09/30/2021", "Measure": "Measure 4"},
          {"Value": 0.031, "Date": "09/30/2021", "Measure": "Measure 3"},
          {"Value": 0.123, "Date": "09/30/2021", "Measure": "Measure 2"},
          {"Value": -0.475, "Date": "09/30/2021", "Measure": "Measure 1"}
        ]
      },
      "width": 500,
      "height": 250,
      "resolve": {"scale": {"color": "independent"}},
      "layer": [
        {
          "mark": "bar",
          "encoding": {
            "y": {
              "field": "Value",
              "type": "quantitative",
              "axis": {"format": ".1%"},
              "sort": "descending"
            },
            "x": {"field": "Date", "type": "nominal", "axis": {"labelAngle": -45}},
            "color": {"field": "Measure", "type": "nominal"}
          }
        },
        {
          "transform": [
            {
              "stack": "Value",
              "groupby": ["Date"],
              "as": ["lower", "upper"],
              "sort": [{"field": "Measure", "order": "descending"}]
            },
            {"calculate": "(datum.lower + datum.upper) / 2", "as": "midpoint"}
          ],
          "mark": {"type": "text"},
          "encoding": {
            "y": {"field": "midpoint", "type": "quantitative"},
            "x": {"field": "Date", "type": "nominal"},
            "color": {
              "field": "Measure",
              "type": "nominal",
              "scale": {"range": ["white"]},
              "legend": null
            },
            "text": {"aggregate": "sum", "field": "Value"}
          }
        }
      ]
    }