简体   繁体   中英

How can I avoid showing unused legend entries in vega-lite?

I have multiple plots (pie charts, scatterplots, barcharts) in a dashboard, all of them are colored by a third attribute. Therefore I created a custom color scale to use in every plot. Now, the whole scale is shown in every legend in every plot, even if only 3 of the colors are in fact necessary, as there are no data points for the other colors. How can I make vega-lite showing only those legend entries with existing data. I need a global solution, as I have different data sets to which I want to apply the same code of course. Thanks in advance for your answers!

未使用的图例条目

   EEKData = {
        "values": [
        {EEK: "A+", Energieträger: "Wärmepumpe", "frequency": 1},
        {EEK: "A", Energieträger: "Gas", "frequency": 16},
        {EEK: "A", Energieträger: "Wärmepumpe", "frequency": 5},
        {EEK: "A", Energieträger: "Fernwärme", "frequency": 7},
        {EEK: "B", Energieträger: "Fernwärme", "frequency": 14},
        {EEK: "C", Energieträger: "Wärmepumpe", "frequency": 201},
        {EEK: "D", Energieträger: "Wärmepumpe", "frequency": 248},
        {EEK: "E", Energieträger: "Wärmepumpe", "frequency": 210},
        {EEK: "F", Energieträger: "Wärmepumpe", "frequency": 200},
        {EEK: "H", Energieträger: "Gas", "frequency": 28}
        ]
    };

 custom_scale = {
  "domain": ["Fernwärme", "Gas", "Gas dezentral", "BHKW", "Pellet",
        "Öl", "Wärmepumpe", "Elektro-Nachtspeicher", "Sonstiges"],
   "range": ["#0070C0", "#ED6011", "#FF0900", "#C00025", "#843C0C",
       "#000000", "#70AD47", "#6C7406", "#595959"]
};

const spec = {
    data: {name: 'values'},
        mark: {type: 'bar', size: 20, opacity: 1},
        encoding: {
            x: {field: 'EEK', type: 'nominal', sort: ["A+", "A", "B", "C", "D", "E", "F", "G", "H"], title: null, axis: {labelAngle: 0}},
            y: {field: 'frequency', type: 'quantitative', title: null},
            color: {field: 'Energieträger', type: 'nominal', scale: customScale},

        }
    },
}

return <VegaLite
    spec={spec}
    data={EEKData}
/>

Vega-Lite will use all the colours you provide in your scale. Do you need to set a custom domain and range? If you want the functionality you describe, you need to let VL calculate the colours for you automatically and then it will use only the ones in the data.

Another option is to provide the color in a field in your data if you need certain colours for specific categories.

我通过根据出现的类别过滤每个数据集的自定义颜色数组,然后使用子数组作为色标解决了这个问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM