Search code examples
vega-lite

add Total label on top of stacked bar in Vega-Lite


Need your help again.

I am trying to add total label on each stacked bar, but getting that sum seen on each layer. I just need one on top

Here is screenshot what i am currently achieved screenshot of graph

This what i tried:

Vega-Lite Editor

Thank you


Solution

  • It looks like you are on the right track with your solution; the easiest way to do it is to include the aggregate transform on the text layer itself, as follows:

    {
      "transform": [
        {
          "aggregate": [{"op": "sum", "field": "value", "as": "total"}],
          "groupby": ["x"]
        }
      ],
      "mark": "text",
      "encoding": {
        "text": {"field": "total"},
        "y": {"field": "total"}
      }
    }
    

    Essentially what is happening is that the text layer is using the same data as the stacked bar chart, but is commputing the sum grouped by the "x" field, which only gives you one data entry per "x" value. In your solution, while you have computed the "summed" value appropriately, you still have one data entry for every segment in each bar, which results in the multiple labels.

    A good way to see what is happening with the data is to use the "Data Viewer" in the online editor. Compare the data from your solution (top) with the transformed data using the approach above (bottom):

    snippet of a data table with multiple entries for each "x" value

    full data table with a single entry for each "x" value