如何在VegaLite中使用数组数据?
我想将数据用作数组
dates = [1, 2, 3]
prices1 = [1, 2, 1]
prices2 = [1.5, 1, 2]
代替了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 }
]
的完整示例
{
"$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"}
}
}
答案 0 :(得分:1)
您可以使用一系列数据转换来实现此目的:
结果是这样的:
{
"$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"}
}
}
要探究转换的作用,在Vega Editor中打开图表并使用 Data Viewer 标签来探究每个转换如何修改基础数据会很有用。 / p>