Reputation: 15386
How to use array data in VegaLite?
I want to use data as arrays
dates = [1, 2, 3]
prices1 = [1, 2, 1]
prices2 = [1.5, 1, 2]
Instead of the table data that's traditionally used in VegaLite
[
{ "date": 1, "price": 1, "symbol": 1 },
{ "date": 2, "price": 2, "symbol": 1 },
{ "date": 3, "price": 1, "symbol": 1 },
{ "date": 1, "price": 1.5, "symbol": 2 },
{ "date": 2, "price": 1, "symbol": 2 },
{ "date": 3, "price": 2, "symbol": 2 }
]
Full example with playground
{
"$schema": "https://vega.github.io/schema/vega-lite/v4.json",
"description": "Stock prices of 5 Tech Companies over Time.",
"data": {
"values": [
{ "date": 1, "price": 1, "symbol": 1 },
{ "date": 2, "price": 2, "symbol": 1 },
{ "date": 3, "price": 1, "symbol": 1 },
{ "date": 1, "price": 1.5, "symbol": 2 },
{ "date": 2, "price": 1, "symbol": 2 },
{ "date": 3, "price": 2, "symbol": 2 }
]
},
"mark": {
"type": "line",
"point": {
"filled": false,
"fill": "white"
}
},
"encoding": {
"x": {"field": "date", "type": "quantitative"},
"y": {"field": "price", "type": "quantitative"},
"color": {"field": "symbol", "type": "nominal"}
}
}
Upvotes: 3
Views: 1649
Reputation: 86463
You can achieve this using a sequence of data transforms:
The result is something like this:
{
"$schema": "https://vega.github.io/schema/vega-lite/v4.json",
"description": "Stock prices of 5 Tech Companies over Time.",
"data": {
"values": [
{"date": [1, 2, 3], "prices1": [1, 2, 1], "prices2": [1.5, 1, 2]}
]
},
"transform": [
{"flatten": ["date", "prices1", "prices2"]},
{"fold": ["prices1", "prices2"], "as": ["symbol", "price"]},
{"calculate": "slice(datum.symbol, -1)", "as": "symbol"}
],
"mark": {"type": "line", "point": {"filled": false, "fill": "white"}},
"encoding": {
"x": {"field": "date", "type": "quantitative"},
"y": {"field": "price", "type": "quantitative"},
"color": {"field": "symbol", "type": "nominal"}
}
}
To explore what the transforms are doing, it can be useful to open the chart in the Vega Editor and use the Data Viewer tab to explore how each transform modifies the underlying data.
Upvotes: 4