我正在寻找一种为多字段数据输出自定义图例的方法。理想情况下,我想对我可能拥有的所有字段进行静态颜色编码(总共可能有大约 20 个),并按颜色和任意文本输出图例,或者至少输出一个字段名称。
在下面的示例中,我想要一个图例来显示“蓝色描边
系列 1 红色描边
系列 2”。
我很乐意展示我目前所拥有的东西,但我尝试过将“图例”放置在它可能适合的任何地方,但它没有做任何事情。
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"data": {
"values": [
{"x": 1, "y": 10},
{"x": 2, "y": 7},
{"x2": 1, "y2": 11},
{"x2": 2, "y2": 12}
]
},
"encoding": {"x": {"type": "quantitative"},
"y": {"type": "quantitative"}},
"layer": [
{
"layer": [
{
"mark": "line",
"encoding": {
"x": {"field": "x"},
"y": {"field": "y"},
"color": {"value": "blue"}
}
},
{
"mark": "line",
"encoding": {
"x": {"field": "x2"},
"y": {"field": "y2"},
"color": {"value": "red"}
}
}
]
}
]
}
最佳答案
Vega-Lite 中的图例是根据编码创建的,因此如果您希望显示图例,则需要构建适当的编码。对于分层图表,实现此目的的一种方法是为每个图层使用datum
编码,然后您可以构建一个自定义色标,将这些编码映射到所需的颜色。例如(open in editor):
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"data": {
"values": [
{"x": 1, "y": 10},
{"x": 2, "y": 7},
{"x2": 1, "y2": 11},
{"x2": 2, "y2": 12}
]
},
"encoding": {
"x": {"type": "quantitative"},
"y": {"type": "quantitative"},
"color": {
"type": "nominal",
"scale": {"domain": ["Series1", "Series2"], "range": ["blue", "red"]}
}
},
"layer": [
{
"mark": "line",
"encoding": {
"x": {"field": "x"},
"y": {"field": "y"},
"color": {"datum": "Series1"}
}
},
{
"mark": "line",
"encoding": {
"x": {"field": "x2"},
"y": {"field": "y2"},
"color": {"datum": "Series2"}
}
}
]
}
关于plot - Vega-Lite:添加不基于字段值/自动颜色/自动形状的自定义图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70221517/