Search code examples
jsonchartsvisualizationvega-lite

Fill missing data with 0 in specified date range with Vega-Lite


I have to render a line-chart that consumes data from an API and it only returns values for the days that do have some data. For the days where there is no data, it does not return an entry with 0 as it'd be expected.

This means that the chart doesn't represent values with 0, which is an issue.

I can't modify this API, so my question would be if there is a way I can tell vega-lite to render data within a date range and, if there is no data for some day, show it as 0.

I guess I'd be able to transform the data before sending it to my react-vega component, but if this can be done by vega-lite, it'd be much better.


Solution

  • You can use impute (you have to supply dates converted to number in the impute though - I have raised a bug here)

    The spec below imputes a zero value for 2012-01-05:

    enter image description here

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      "description": "Using utc scale with local time input.",
      "data": {
        "values": [
          {"date": "2012-01-01", "price": 150},
          {"date": "2012-01-02", "price": 100},
          {"date": "2012-01-03", "price": 170},
          {"date": "2012-01-04", "price": 165},
          {"date": "2012-01-06", "price": 200}
        ]
      },
      "transform": [
        {
          "impute": "price",
          "key": "date",
          "value": 0,
          "keyvals": [
            1325376000000,
            1325462400000,
            1325548800000,
            1325635200000,
            1325721600000,
            1325721600000
          ]
        },
        {"timeUnit": "day", "field": "date", "as": "dateTU"}
      ],
      "mark": "line",
      "encoding": {
        "x": {"field": "date", "timeUnit": "date"},
        "y": {"field": "price", "type": "quantitative"}
      }
    }