susielu / d3-legend

A reusable d3 legend component.
http://d3-legend.susielu.com/
Apache License 2.0
727 stars 104 forks source link

Legend filtering #31

Closed gemfarmer closed 7 years ago

gemfarmer commented 8 years ago

First of all, great work @susielu ! I have really enjoyed using your legend.

A useful setting would be a .filter() or .cull() method that made it easy to only display legend cells that are in a particular dataset.

I am happy to do this when I can get around to it!

An example implementation might look something like below, where only the 0th, 1st, and 3rd cells are appended to the legend

var dataset = [0, 150, 500, 250, 500, 250, 500];

var quantize = d3.scale.quantize()
  .domain([0, 1000])
  .range([0,1,2,3,4]);

var svg = d3.select(this)
  .select("svg");

svg.append("g")
  .attr("class", "legendQuant");

var legend = d3.legend.color()
  .labelFormat(d3.format.si)
  .useClass(false)
  .filter(_.uniq(dataset)) // _.uniq(dataset) => [0,1,3]
  .scale(quantize);
susielu commented 8 years ago

Hmm interesting. Just to clarify the dataset should actually be a list of values that match the domain is that right? Your example seems to imply it's a list of values that match the range.

gemfarmer commented 8 years ago

@susielu Hmm...my example is confusing. The idea would be to filter by the ranges that are represented in a dataset. I updated the example to make more sense.

This following comment indicates that those are the unique ranges that would be displayed in the legend.

// _.uniq(dataset) => [0,1,3]
susielu commented 7 years ago

Hi @gemfarmer

I implemented a .cellFilter attribute which takes a function. This function is run as a filter function against the array of cells. If you have a function(d){ return true or false }, d has a .data and a .label property as it iterates over each cell it will display. Create a false condition for any cells you want to exclude from being displayed. You will still need to determine the unique values outside of the legend component itself, but I think this allows for more flexibility to the user.

An example here: http://d3-legend.susielu.com/#color-ordinal

Thanks, Susie

gemfarmer commented 7 years ago

@susielu this is exactly what I was suggesting. Thanks for implimenting!