首页 > 解决方案 > 为什么 vega-lite 为图例设置为空的图层绘制图例?

问题描述

我为两类数据中的每一个都有一个单独的图层。每个类别有两个子类别。只有第一个顶级类别应该有图例。所以我把legend: null第二个类别放在resolve最顶层,做传说independent。但它不起作用。这是情节,下面是我的代码。我希望只看到ab在传说中。

类别图

<!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>

标签: vega-lite

解决方案


除非您另有说明,否则独立图例仍将共享色标。您可以通过指定来更改它resolve.scale

在你的情况下,而不是

"resolve": {"legend": {"color": "independent"}}

你应该使用

"resolve": {"scale": {"color": "independent"}}

否则,尽管图例是独立的,但仍将共享天平。如果需要,您可以调整每层使用的配色方案来区分这些点。

在这里查看它的实际效果:

在此处输入图像描述


推荐阅读