Search code examples
data-visualizationvega-lite

How to add text mark to a Vega Lite grouped bar chart


I wasn't able to add a text mark layer to a grouped bar chart, I've tried editing the Vega Lite example to add sum label on top of every bar:

enter image description here https://vega.github.io/editor/#/examples/vega-lite/bar_grouped

But what happens is either "layer" property wasn't accepted, or bars get squashed into one bar. How to make this happen?


Solution

  • When you want to add a text mark to a faceted chart, the pattern to use is a Layered view within a Facet Operator.

    For example (vega editor):

    {
      "data": {"url": "data/population.json"},
      "transform": [
        {"filter": "datum.year == 2000"},
        {"calculate": "datum.sex == 2 ? 'Female' : 'Male'", "as": "gender"}
      ],
      "width": {"step": 12},
      "facet": {"field": "age", "type": "ordinal"},
      "spec": {
        "encoding": {
          "y": {
            "aggregate": "sum",
            "field": "people",
            "type": "quantitative",
            "axis": {"title": "population", "grid": false}
          },
          "x": {"field": "gender", "type": "nominal", "axis": {"title": ""}}
        },
        "layer": [
          {
            "mark": "bar",
            "encoding": {
              "color": {
                "field": "gender",
                "type": "nominal",
                "scale": {"range": ["#675193", "#ca8861"]}
              }
            }
          },
          {
            "mark": {
              "type": "text",
              "dx": -5,
              "angle": 90,
              "baseline": "middle",
              "align": "right"
            },
            "encoding": {
              "text": {
                "aggregate": "sum",
                "field": "people",
                "type": "quantitative",
                "format": ".3s"
              }
            }
          }
        ]
      },
      "config": {
        "view": {"stroke": "transparent"},
        "facet": {"spacing": 10},
        "axis": {"domainWidth": 1}
      }
    }
    

    enter image description here