-->

dc.js piechart legend - hide if result is 0

2019-07-23 02:42发布

问题:

Is it possible to remove/hide the legends for a piechart if the result is 0?

I have a piechart that has quite a few items in the legend, when there has been some filtering it would be great to remove the legends that are not available.

Any help would be appreciated.

回答1:

Legends do render when their charts are redrawn, but the problem here is that the legend is drawn from the data, and crossfilter doesn't automatically eliminate empty groups.

It would be really great if legends were a chart type, so we could just use a fake group (a.k.a. "data transform"). But no, we need to update .legendables() to filter out the empty bins:

dc.override(pieactChart, 'legendables', function() {
    var legendables = this._legendables();
    return legendables.filter(function(l) {
        return l.data > 0;
    });
});

Fork of your fiddle: http://jsfiddle.net/gordonwoodhull/13t804u6/5/

Note: this only modifies the one (left) chart, you'll have to copy/paste it for each chart (or wrap it in a function) to apply it to other charts.

[I am very stubborn about not wanting such data filtering stuff inside the charts, so I'm not going to suggest this as a feature. Instead, legend should be a chart which takes its data from another chart, and there should be a way to transform that data.]