Search code examples
javascriptdata-visualizationvega-litevega

Remove empty values from grouped bar chart in Vega-lite


Using Vega-lite I'm creating a grouped bar chart where schools are grouped by a Size string variable on the x-axis. The Y-axis is quantitative. I have it almost working but currently each group is including a spot on the x-axis for every school, including ones that aren't in that group and therefore display no data. For example: For example:

How do I ensure that schools only show up in the category that they belong? All but one example I've found online doing this type of thing uses an older version of Vega-lite and trying to reverse engineer them has been fruitless.

var barGroupCreate = {
      $schema: "https://vega.github.io/schema/vega-lite/v5.json",
      data: { values: toolData },
      config: { view: { stroke: "transparent" }, axis: { domainWidth: 1 } },
      spacing: { column: 10 },
      facet: {
        column: {
          field: "Size",
          type: "nominal",
          header: { orient: "bottom" },
        },
      },
      spec: {
        width: { step: 12 },
        mark: "bar",
        encoding: {
          y: {
            aggregate: "sum",
            field: "Contact Hours (Total)",
            title: "Contact Hours",
            axis: { grid: false },
          },
          x: { field: "Name", axis: null },
          color: {
            field: "Size",
            scale: {
              range: [
                "#002D74",
                "#F26852",
                "#2A7DE1",
                "#FFD100",
                "#00A9C5",
                "#3A4A9F",
              ],
            },
          },
        },
      },
    };

Sample of my data (toolData):

"values": [
  {
    "Name": "Alamo",
    "Contact Hours (Total)": 19930352,
    "Size": "Very large",
  },
  {
    "Name": "Alvin",
    "Contact Hours (Total)": 2211352,
    "Size": "Medium",
  },
  {
    "Name": "Amarillo",
    "Contact Hours (Total)": 4363650,
    "Success Points (Total)": 16945,
    "Size": "Large",
  },
  {
    "Name": "Angelina",
    "Contact Hours (Total)": 1983398,
    "Size": "Medium",
  },
  {
    "Name": "Austin",
    "Contact Hours (Total)": 14027493,
    "Size": "Very large",
  },
  {
    "Name": "Blinn",
    "Contact Hours (Total)": 7594730,
    "Size": "Large",
  },

Solution

  • You can do this by adding

    resolve: {scale: {x: "independent"}}
    

    within barGroupCreate.

    More information at https://vega.github.io/vega-lite/docs/facet.html#resolve