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

Viewed 38

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!

Unused legend entries

   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}
/>
2 Answers

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.

I solved the issue by filtering the array of custom colors for every dataset according to the occurring categories and then using the sub array as color scale.

Related