Reputation: 3616
I've set up a legend within my D3 visualization and the legend currently includes all possible 'vehicles' and their color designation.
I set the colors like so:
var color = d3.scale.ordinal()
.domain(['bike', 'motorcycle', 'car', 'van', 'truck'])
.range(['#00986F', '#41A5D1', '#695998', '#E2595B', '#AA595B']);
...and I use this scale like so:
var vehiclesLegend = vehiclesLegendWrapper.selectAll('.vehiclesLegendSquare')
.data(color.range())
.enter().append('g')
.attr('class', 'vehiclesLegendSquare')...
The problem is that not all of my datasets contain all of the possible vehicles so my legend will still show 'truck', for example, even when there are no trucks in the data.
Is there a simple way to exclude certain vehicle/color combos from legend based on the dataset?
Upvotes: 1
Views: 103
Reputation: 108507
Many ways to solve this. I'd just use a filter with the domain:
var vehiclesLegend = vehiclesLegendWrapper.selectAll('.vehiclesLegendSquare')
.data(color.domain()) //<-- going to use domain instead
.enter().append('g')
.filter(function(d){
return (d in dataset); //<-- d would be 'truck', 'car', etc.. (pseduo-code, fix for your real dataset)
})
.attr('class', 'vehiclesLegendSquare')
...
.style('fill', function(d) {
return color(d); //<-- back to color
})
Upvotes: 2