Search code examples
jsonvisualizationdata-analysisvega-litevega

Vega chart count aggregation displays nothing if data values is empty array, how to fix this?


I have this small Vega chart spec which should display the count of the FieldToCount:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "encoding": {
    "text": {
      "aggregate": "count",
      "field": "FieldToCount"
    }
  },
  "data": {"values": [{"FieldToCount": 1}, {"FieldToCount": 1}]},
  "mark": {
    "type": "text",
    "fontSize": 20
  }
}

This works but as soon as I have zero item in the values it displays nothing. So this does not work:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "encoding": {
    "text": {
      "aggregate": "count",
      "field": "FieldToCount"
    }
  },
  "data": {"values": []},
  "mark": {
    "type": "text",
    "fontSize": 20
  }
}

So the question is how to make sure it displays 0?


Solution

  • This works for me.

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
      "data": {"values": [{"FieldToCount": 1}, {"FieldToCount": 1}]},
      "layer": [
        {
          "data": {"values": [{"q": 1}]},
          "encoding": {
            "text": {
              "condition": {"test": "length(data('source_0')) > 0", "value": ""},
              "value": "0"
            }
          },
          "mark": {"type": "text", "fontSize": 20}
        },
        {
          "transform": [
            {"aggregate": [{"op": "count", "field": "FieldToCount", "as": "c"}]}
          ],
          "encoding": {"text": {"field": "c"}},
          "mark": {"type": "text", "fontSize": 20}
        }
      ]
    }