Reputation: 685
I'm playing with vega-lite v5 and the new parameters and wanted to change the order of marks using an input element:
Open the Chart in the Vega Editor
Is that possible?
I looked into the examples in the documentation but neither on x
's order property or with an order
encoding I was able to use the param.
Upvotes: 3
Views: 627
Reputation: 66
Yes you can do this by sorting the data with a window
transform. Although undocumented as of VL 5.1.0, window properties can be parameterised with signal
values (and should take expr
values with the next update). Here's a working example that separates your input element into the field to sort by and the direction to sort.
Open below example in Vega Editor
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"data": {
"values": [
{"a": "A", "b": 28},
{"a": "B", "b": 55},
{"a": "C", "b": 43},
{"a": "D", "b": 91},
{"a": "E", "b": 81},
{"a": "F", "b": 53},
{"a": "G", "b": 19},
{"a": "H", "b": 87},
{"a": "I", "b": 52}
]
},
"params": [
{"name": "sortChoice", "value":"x",
"bind": {"input": "select", "options": ["x", "y","-x","-y"]}},
{"name": "sortBy",
"expr":"sortChoice==='x'|| sortChoice==='-x' ? 'a':'b'"},
{"name": "sortOrder",
"expr":"sortChoice==='x'|| sortChoice==='y' ? 'ascending':'descending'"}
],
"transform": [
{
"sort": [
{"field": {"signal": "sortBy"}, "order": {"signal": "sortOrder"}}
],
"window": [{"op": "rank", "as": "sorted"}]
}
],
"mark": "bar",
"encoding": {
"x": {"field": "a", "sort": {"field": "sorted"}},
"y": {"field": "b", "type": "quantitative"}
}
}
The parameter expressions could also be written as
{"name": "sortBy", "expr":"test(/x/, sortChoice) ? 'a':'b'"},
{"name": "sortOrder", "expr":"test(/-/, sortChoice) ? 'descending' : 'ascending'"}
Upvotes: 5