从多列生成图例的最佳方法是使用Fold Transform 将它们折叠成一列,然后让编码为您处理图例。修改您链接到的示例,它可能看起来像这样:(vega editor link):
{
"data": {"url": "data/seattle-weather.csv", "format": {"type": "csv"}},
"encoding": {
"x": {"timeUnit": "yearmonthdate", "field": "date", "type": "temporal"},
"tooltip": [
{"timeUnit": "yearmonthdate", "field": "date", "type": "temporal"},
{"field": "temp_max", "type": "quantitative"},
{"field": "temp_min", "type": "quantitative"}
]
},
"layer": [
{
"transform": [
{"fold": ["temp_min", "temp_max"], "as": ["measure", "temp"]}
],
"mark": {"type": "line"},
"encoding": {
"y": {"field": "temp", "type": "quantitative"},
"color": {"field": "measure", "type": "nominal"}
}
},
{
"mark": "rule",
"selection": {
"hover": {"type": "single", "on": "mouseover", "empty": "none"}
},
"encoding": {
"color": {
"condition": {"selection": {"not": "hover"}, "value": "transparent"}
}
}
}
],
"config": {"axisY": {"minExtent": 30}}
}
请注意,我们已将两个 temp_min/temp_max 层替换为单个层,该层可转换数据并按列名称对颜色进行编码,从而自动生成图例。