I have a plot with a separate layer for each of two categories of data. Each category has two subcategories. Only the first top-level category should have a legend. So I put legend: null
on the second category and put a resolve
at the top level to make the legends independent
. But it's not working. Here's the plot, and below it is my code. I expect to see only a
and b
in the legend.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>legend test</title>
<link rel="stylesheet" href="styles/style.css" />
<script src="https://cdn.jsdelivr.net/npm/vega@5.9.1"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite@4.2.0"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-embed@6.2.2"></script>
</head>
<body>
<div id="plot-div"></div>
<script>
let spec = {
$schema: "https://vega.github.io/schema/vega-lite/v4.json",
description: "sigmatcher",
data: {
values: [
{legendGroup: true, x: 1, y: 1, cat: "a"},
{legendGroup: true, x: 2, y: 2, cat: "b"},
{legendGroup: true, x: 3, y: 4, cat: "a"},
{legendGroup: true, x: 4, y: 8, cat: "b"},
{legendGroup: false, x: 1, y: 11, cat: "c"},
{legendGroup: false, x: 2, y: 12, cat: "d"},
{legendGroup: false, x: 3, y: 14, cat: "c"},
{legendGroup: false, x: 4, y: 18, cat: "d"},
{legendGroup: false, x: 5, y: 26, cat: "c"},
]},
width: 400,
height: 400,
resolve: {
legend: {
color: "independent",
}
},
layer: [{
transform: [{
filter: {
field: "legendGroup",
equal: true
}}],
encoding: {
x: {
field: "x",
type: "quantitative"
},
y: {
field: "y",
type: "quantitative"
},
color: {
field: "cat",
type: "nominal"
}
},
mark: {
type: "point"
}
}, {
transform: [{
filter: {
field: "legendGroup",
equal: false
}}],
encoding: {
x: {
field: "x",
type: "quantitative"
},
y: {
field: "y",
type: "quantitative"
},
color: {
field: "cat",
type: "nominal",
legend: null
}
},
mark: {
type: "point"
}
}]};
vegaEmbed("#plot-div", spec);
</script>
</body>
</html>
Independent legends will still share a color scale unless you specify otherwise. You can change this by specifying resolve.scale
.
In your case, instead of
"resolve": {"legend": {"color": "independent"}}
you should use
"resolve": {"scale": {"color": "independent"}}
Otherwise the scales will still be shared despite the legends being independent. If desired, you can then adjust the color schemes used by each layer to distinguish the points.
See it in action here: