Using window transform to impute missing values by averaging the previous and next values.

Using window transform to impute missing values in a line chart by averaging the previous and next values.

View this example in the online editor

Vega-Lite JSON Specification

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "Using window transform to impute missing values in a line chart by averaging the previous and next values.",
  "width": 300,
  "data": {
    "values": [
      {"a": "Jan 1, 2000", "b": 28},
      {"a": "Jan 2, 2000", "b": 55},
      {"a": "Jan 3, 2000", "b": null},
      {"a": "Jan 4, 2000", "b": 65},
      {"a": "Jan 5, 2000", "b": 43},
      {"a": "Jan 6, 2000", "b": null},
      {"a": "Jan 7, 2000", "b": 55},
      {"a": "Jan 8, 2000", "b": 43}
    ]
  },
  "transform": [{
    "window": [{
      "op": "lag",
      "field": "b",
      "as": "prev"
    },{
      "op": "lead",
      "field": "b",
      "as": "next"
    }]
  }, {
    "calculate": "datum.b === null ? (datum.prev + datum.next)/2 : datum.b",
    "as": "b"
  }],
  "mark": {"type": "line", "point": true},
  "encoding": {
    "x": {"timeUnit": "yearmonthdate", "field": "a", "type": "temporal", "axis": {"format": "%d %b"}},
    "y": {"field": "b", "type": "quantitative"}
  }
}