问题描述
我正在Vega Lite中看到一个我不理解的奇怪行为。
使用此示例图表:
{
"$schema": "https://vega.github.io/schema/vega-lite/v4.json","data": {
"values": [
{"model": "Sedan","color": "Red","sales": 28},{"model": "Sedan","color": "Silver","sales": 17},"color": "Black","sales": 34},{"model": "Pickup","sales": 20},"sales": 71},"sales": 14},{"model": "Minivan","sales": 52},"sales": 31},"sales": 45}
]
},"concat": [{
"mark": "bar","encoding": {
"x": {"field": "model"},"y": {"aggregate": "sum","field": "sales"}
}
},{
"mark": "arc","encoding": {
"color": {"field": "color"},"theta": {"aggregate": "sum","field": "sales"}
}
}]
}
结果很简单:
现在,观察当我在第一个图表的 transform部分中生成一个新字段“ flag”时,会发生什么,以突出显示一个特定的条(拾取):
{
"$schema": "https://vega.github.io/schema/vega-lite/v4.json","transform": [
{"calculate": "datum.model == 'Pickup'","as": "flag"} // <- "flag" defined here
],"field": "sales"},"color": {"field": "flag"} // <- and used here
}
},// <- the second chart
"encoding": { // shouldn't even see
"color": {"field": "color"},// the new "flag" field
"theta": {"aggregate": "sum","field": "sales"} //
}
}]
}
该标记有效(拾取栏突出显示),即使我在第一个图表的上下文中定义了它,它也会影响第二个图表及其图例:
解决方法
问题在于,在复合图中,Vega-Lite默认使用共享比例(请参见Scale and Guide Resolution)。
如果您希望色阶独立,可以设置
"resolve": {"scale": {"color": "independent"}}
完整规格如下所示(view in editor):
{
"$schema": "https://vega.github.io/schema/vega-lite/v4.json","data": {
"values": [
{"model": "Sedan","color": "Red","sales": 28},{"model": "Sedan","color": "Silver","sales": 17},"color": "Black","sales": 34},{"model": "Pickup","sales": 20},"sales": 71},"sales": 14},{"model": "Minivan","sales": 52},"sales": 31},"sales": 45}
]
},"concat": [
{
"mark": "bar","transform": [{"calculate": "datum.model == 'Pickup'","as": "flag"}],"encoding": {
"x": {"field": "model"},"y": {"aggregate": "sum","field": "sales"},"color": {"field": "flag"}
}
},{
"mark": "arc","encoding": {
"color": {"field": "color"},"theta": {"aggregate": "sum","field": "sales"}
}
}
],"resolve": {"scale": {"color": "independent"}}
}