如何在Vega-Lite中从对象提取数组作为数据源?
问题描述
现有如下JSON数据对象:
{ "station": { "id": {"name": "SNK"}, "position": {"lat":0.00,"lon":0.00} }, "datagram": [ { "date": {"iso-8601": "1966-01-12"}, "air": { "temp": {"mean": -17.8} }, "precip": {"1d": 1} } ] }
需要使用datagram数组内的以下数据:
date.iso-8601air.temp.mean
因此需要直接将该数组指定为数据源。
我尝试通过Transform的Calculate创建新数组d,配置片段如下:
data: { url: 'http://...', format: {type: 'json'} }, transform: [ {calculate: "datum.datagram", "as": "d"} ], encoding: { x: {type: 'temporal', field: 'd.date.iso_date_time', title: 'Date'}, y: {type: 'quantitative', field: 'd.air.temp.mean', title: '[°C]'} }
但该方法无效,报错:
vega@5.22.1:1 WARN Infinite extent for field "d.date.iso_date_time": [Infinity, -Infinity]
问题:在原生Vega-Lite中,如何从对象中提取数据表作为数据源?
完整配置如下:
{ $schema: 'https://vega.github.io/schema/vega-lite/v5.json', description: '', width: 'container', data: { url:'', format: {type: 'json'} }, transform: [ {calculate: "datum.datagram", "as": "d"} ], mark: 'circle', encoding: { x: {type: 'temporal', field: 'd.time.iso_date_time', title: 'Date'}, y: {type: 'quantitative', field: 'd.air.temp.mean', title: '[°C]'} } };
解决方案:原生JS长期方案
这种情况下,可在Vega-Lite外部直接赋值数据数组,无需调用Calculate和Flatten:
var vegaLiteSpec = { $schema: 'https://vega.github.io/schema/vega-lite/v5.json', // 定义空数据: data: {values: []}, // ...其余配置... }; fetch('https://...') .then(res => res.json()) .then((out) => { vegaLiteSpec.data.values = out.datagram; vegaEmbed('#div-chartElement', vegaLiteSpec); }) .catch(err => { throw err });
内容的提问来源于stack exchange,提问作者Mruk
相关产品推荐
相关产品推荐

