Search code examples
plottextlabeldata-visualizationvega-lite

Vega-Lite - How to plot stacked bar with labels in each nar?


Given a stacked bar plot, how can I add labels with the values of each of the bar?

Below is an example of what I'm trying to do: Stacked bar example


Solution

  • You can do this by layering a bar mark and a text mark. For example (open in editor):

    {
      "data": {"url": "data/barley.json"},
      "width": 400,
      "encoding": {
        "x": {
          "type": "quantitative",
          "aggregate": "sum",
          "field": "yield",
          "stack": "zero"
        },
        "y": {"type": "nominal", "field": "variety"}
      },
      "layer": [
        {
          "mark": "bar",
          "encoding": {"color": {"type": "nominal", "field": "site"}}
        },
        {
          "mark": {"type": "text", "color": "white", "dx": -15, "dy": 3},
          "encoding": {
            "detail": {"type": "nominal", "field": "site"},
            "text": {
              "type": "quantitative",
              "aggregate": "sum",
              "field": "yield",
              "format": ".1f"
            }
          }
        }
      ]
    }
    

    enter image description here