vega-lite - 使用数据作为数组而不是 Vega Lite 的表
问题描述
如何在 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"}
}
}
解决方案
您可以使用一系列数据转换来实现这一点:
- 将数据数组转换为普通表条目的扁平化转换
- 将两个价格列转换为带有标签列的单个价格列的折叠转换
- 使用适当的Vega 表达式进行计算转换,以从您的价格标签中提取数字。
结果是这样的:
{
"$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 编辑器中打开图表并使用数据查看器选项卡来探索每个转换如何修改基础数据会很有用。
推荐阅读
- android - 大厅座位布局设计安卓
- java - 使用阻塞队列的对象池在死锁中运行
- mysql - MYSQL - 将数据存储为枚举数值是否比存储具有完整值的数据更好?
- jquery - 为什么 $('.myClass').on("input propertychange", function() {}) 总是在 $(document).on("input propertychange", ".myClass", function() {)) 之前调用?
- swift - 二元运算符 '+=' 不能应用于类型的操作数。
- wpf - Popup 中的 ItemsControl 复制了添加的第一个项目
- node.js - 在没有第三方服务的情况下使用 Node JS 发送 SMS
- ios - Swift:如何从 CNContactPickerViewController 搜索选项中隐藏“SIRI Found IN APPS”选项?
- javascript - JavaScript / SAPUI5 如何将文件附加到指定位置并将其导出到指定位置?
- android - 如何实现一个自定义的 ImageView,在其中我可以在视图中绘制 Bitmap 后回收它?