如何在Vega-Lite中叠加两个不同Elasticsearch数据源的散点图?
问题描述
我想要叠加两个基于不同Elasticsearch索引数据源创建的散点图。目前可以使用layer层叠同一数据源的两个图表,但无法实现双数据源的散点图叠加,报错信息为:
Cannot set properties of undefined (setting 'format')
现有代码结构如下:
{ "$schema": "https://vega.github.io/schema/vega-lite/v4.json", "layer": [ { "data": { "url": { "index": "A", "body": { "size": 10000, "_source": ["A_a", "A_b"], }, "format": {"property": "hits.hits"} }, "mark": {"type": "circle"}, "encoding": { ... } } }, { "data": { "url": { "index": "B", "body": { "size": 10000, "_source": ["B_a", "B_b"], }, "format": {"property": "hits.hits"} }, "mark": {"type": "circle"}, "encoding": { ... } } } ] }
我尝试将"format": {"property": "hits.hits"}改为"format": {"property": "hits.hits._source"},但问题仍未解决。请问该如何调整format以适配双数据源?
解决方案
报错的核心原因是你把format配置嵌套在了url对象内部,而在Vega-Lite语法中,format是data对象的直接属性,需要和url同级放置,不能嵌套在url里。
修改后的正确代码结构如下:
{ "$schema": "https://vega.github.io/schema/vega-lite/v4.json", "layer": [ { "data": { "url": { "index": "A", "body": { "size": 10000, "_source": ["A_a", "A_b"] } }, "format": {"property": "hits.hits"} // 移至url同级 }, "mark": {"type": "circle"}, "encoding": { "x": {"field": "_source.A_a", "type": "quantitative"}, "y": {"field": "_source.A_b", "type": "quantitative"} } }, { "data": { "url": { "index": "B", "body": { "size": 10000, "_source": ["B_a", "B_b"] } }, "format": {"property": "hits.hits"} // 同样移至url同级 }, "mark": {"type": "circle", "color": "red"}, // 可设置不同颜色区分数据源 "encoding": { "x": {"field": "_source.B_a", "type": "quantitative"}, "y": {"field": "_source.B_b", "type": "quantitative"} } } ] }
额外说明:
- 由于
format指定的是hits.hits,所以每个数据项的业务字段都在_source下,编码时需要用_source.字段名的形式引用。 - 如果想直接使用字段名(无需
_source前缀),可以把format的property设置为hits.hits._source,此时编码时直接写字段名即可,比如"x": {"field": "B_a", "type": "quantitative"}。
内容的提问来源于stack exchange,提问作者yelo95
相关产品推荐
相关产品推荐

