'Forcing the legend in Vega chart to draw (and then using it for data filtering)

I have created a stacked bar chart where the dimension for the color of the stacked bars is selected from a drop down. (Can be Country, Fruit Name, etc.)

In the legend box I want to show colors assigned to fruit names. This shows fine when bars are stacked by fruit name

Fruit Name
* apple
* lemon
* ...

but otherwise is undefined

Fruit Name
* undefined

How can I force the legend to draw always?

Why do I want to do that? I would like to make the legend interactive, so that you can use it for filtering of the data shown in the graph. That way I could select - say - apple and plum in the legend but stack the bars by country or the order status. (Nice for data exploration.)



Solution 1:[1]

The data source for the domain of the color scale needs to be changed from deliveries to fruit.

    {
      "name": "colscalefruitname",
      "type": "ordinal",
      "domain": {"data": "deliveries", "field": "fruitname"},
      "range": {"scheme": "category20c"}
    },

Here is an updated chart.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 az5112