Apply a filter transform to a legend

I’m using a basic filter transform, but the legend shows entries for data that has been filtered out. Is there a way to make the legend only show data that is allowed by the filter?

Plot Scatterplot / Michal Charemza | Observable shows the issue. If I define some data:

data = FileAttachment("penguins.csv").csv({typed: true})

And then plot it, but filtered:

Plot.plot({
  inset: 8,
  grid: true,
  color: {
    legend: true,
  },
  marks: [
    Plot.dot(data, {x: "flipper_length_mm", y: "body_mass_g", stroke: "sex",
                    filter: row => row.sex === 'MALE'})
  ]
})

The filter on the data applies fine, showing only MALE in this case, but the legend continues to show FEMALE and null.

Screenshot 2024-07-13 at 14.46.45

The purpose of the filter option is to filter out data without changing the domain. If you only want filtered values to show up you can filter data directly:

Plot.dot(data.filter(row => row.sex === 'MALE'), {x: "flipper_length_mm", y: "body_mass_g", stroke: "sex"})

Alternatively you can set the domain directly, e.g.

  color: {
    legend: true,
    domain: ["MALE"],
  },
1 Like

Ah thanks!