timthoe
timthoe

Reputation: 95

Extending step-after vega-lite graph to todays date

I am trying to make a step-after graph in vega-lite like this example https://vega.github.io/vega-lite/examples/line_step.html. It has values on discrete dates. I want to extend the graph so the last step goes all the way to today´s date (making it an actual step and not just a vertical line at the last date in the data). I tried but failed to find a way to add a calculated extra row to the data i.e.: {date:<today´s date>, value:<last_value>} Any ideas?

Upvotes: 1

Views: 63

Answers (1)

remsidave
remsidave

Reputation: 87

You can make use of Vega-Lite's window transformation and add a validTo column based on the value of the next row in the validFrom column. Naturally this will yield null for the last row as there is no additional row to take the value from. Then in a next step you can use calculate to fill that gap with now(). Lastly we need to fold the data so that we have validFrom and validTo in the same column.

And voila, the step plot extends until today

enter image description here

Here's the example in vega online editor.
And here's the example from your link with lines extended to now.

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "values": [
      {"validFrom": "2024-05-27", "Value": 100},
      {"validFrom": "2024-05-28", "Value": 120},
      {"validFrom": "2024-05-29", "Value": 90},
      {"validFrom": "2024-05-30", "Value": 110}
    ],
    "format": {
      "parse": {
        "validFrom": "date"
      }
    }
  },
  "transform": [
    {"window": [{"op": "lead", "field": "validFrom", "as": "Lead"}]},
    {"calculate": "datum.Lead == null ? now(): datum.Lead ", "as": "validTo"},
    {"fold": ["validFrom", "validTo"], "as": ["key", "Date"]}
  ],
  "mark": {
    "type": "line"
  },
  "encoding": {
    "x": {"field": "Date", "type": "temporal"},
    "y": {"field": "Value", "type": "quantitative"}
  }
}

Upvotes: 0

Related Questions