Reputation: 757
I'm looking for a way to output custom legends for multi-field data. Ideally, I'd like to statically color-code all the fields I may have (in total there might be about 20), and output legends per color and arbitrary text, or at least a field name.
In the example below, I'd like a legend to show "blue stroke
Series 1 red stroke
Series 2".
I'd be happy to show what I have at the moment, but I have tried placing "legend" seemingly everywhere it may fit, and it doesn't do anything.
{
"$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"}
}
}
]
}
]
}
Upvotes: 2
Views: 1198
Reputation: 86453
Legends in Vega-Lite are created from encodings, so if you want a legend to be shown you need to construct an appropriate encoding. For layered charts, one way to do this is using a datum
encoding for each layer, and then you can construct a custom color scale mapping these encodings to the desired color. For example (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"}
}
}
]
}
Upvotes: 2