az5112
az5112

Reputation: 642

Filtering concated charts using legend in Vega-Lite

I hit a snag trying to create two concat-ed charts filtered by legend (selection.bind = "legend").

After a bit of head scratching I was able to reduce the issue to the following (this is based on one of the examples in the documentation):

  1. Example 1 - works as expected - clicking a cylinder number on the legend filters the display on the left chart. (I did not implement any filtering for the chart on the right.)

  2. Example 2 - does not work - Here I have just swapped the two charts.
    I was assuming that now the chart on the right would become interactive (that is it will be filtered after clicking the legend). This does not work.

Is it a bug or am I misunderstanding some basic concept?

Upvotes: 1

Views: 1030

Answers (1)

jakevdp
jakevdp

Reputation: 86310

You have two charts sharing the same legend, and two different legend specifications (one interactive, one not). When you concatenate two charts, Vega-Lite shares scales and legends by default, meaning that it has to choose one of the legend specifications to honor, and one to ignore. The choice the library makes is to honor the first and ignore the second. This is why the legend reflects whatever is specified in the left-most chart of your specification.

The way around this is to set the legend color resolve to independent, so each chart specifies its own legend, and to explicitly set the legend to null to hide it for the chart you don't want a legend for. Modifying your second example (open in editor):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "data": {"url": "data/cars.json"},
  "concat": [
    {
      "mark": "point",
      "encoding": {
        "x": {"field": "Horsepower", "type": "quantitative"},
        "y": {"field": "Miles_per_Gallon", "type": "quantitative"},
        "opacity": {"field": "Cylinders", "type": "nominal", "legend": null}
      }
    },
    {
      "mark": "point",
      "selection": {
        "myCyli": {"type": "multi", "fields": ["Cylinders"], "bind": "legend"}
      },
      "encoding": {
        "x": {"field": "Horsepower", "type": "quantitative"},
        "y": {"field": "Miles_per_Gallon", "type": "quantitative"},
        "opacity": {
          "condition": {
            "selection": "myCyli",
            "field": "Cylinders",
            "type": "ordinal"
          },
          "value": 0
        }
      }
    }
  ],
  "resolve": {"legend": {"opacity": "independent"}}
}

enter image description here

Upvotes: 1

Related Questions