My current minimal example looks like:
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"data": {"values": [
{"year":2022, "week":1, "val":5},
{"year":2022, "week":2, "val":4},
{"year":2022, "week":3, "val":6},
{"year":2021, "week":1, "val":3},
{"year":2021, "week":2, "val":7}
]},
"mark":"line",
"encoding": {
"x":{"field":"week"},
"y":{"field":"val"},
"color":{"field":"year"}
}
}
I would like to calculate the difference of the week's values for this year and the previous year (if one of the values is missing, the difference should not be displayed). So for week 1 I would like to get a difference of 2 (=5 - 3) and for week 2 I would like to get a difference of -3 (= 4 - 7).
It seems like a common thing to do, but I found no examples or documentation solving this problem. I managed to produce the desired output with a kind of very ugly LAG transform but this does only work, if there are the same number of weeks in both years which is not always the case.
Maybe, one could somehow transform the data, that the week's values of this and the previous year appear in the same column?
This works for me.
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"data": {
"name": "myData",
"values": [
{"year": 2022, "week": 1, "val": 5},
{"year": 2022, "week": 2, "val": 4},
{"year": 2022, "week": 3, "val": 6},
{"year": 2021, "week": 1, "val": 3},
{"year": 2021, "week": 2, "val": 7}
]
},
"transform": [
{
"window": [{"op": "lead", "field": "val", "as": "lastVal"}],
"groupby": ["week"]
},
{
"calculate": "datum.lastVal==null?0: datum.val - datum.lastVal",
"as": "diff"
}
],
"mark": "line",
"encoding": {
"x": {"field": "week"},
"y": {"field": "val"},
"color": {"field": "year"}
}
}