-->

dc.js composite chart toggle chart

2020-07-22 20:10发布

问题:

Is there a way to toggle charts on/off in a composite chart?

If I hover over Legend the respective chart is highlighted but it would be nice if we could choose which ones to display (hide/show with Legend, check boxes etc).

I did find reference to hideStack but I don't think this is what I need.

Any ideas?

(Current DC Version: 2.0.0-alpha.2)

回答1:

You're right, legend toggling is currently focused on stacks and not the subcharts of a composite chart.

It may be possible to hack the legend's toggling system, but here is a solution that just adds the toggling functionality as an extension.

We'll just wait until the chart is drawn with the pretransition event, then add our own click handler to each of the legend items. This will use the index of the legend item to create the selector for the corresponding subchart, then toggle its css visibility:

function drawLegendToggles(chart) {
  chart.selectAll('g.dc-legend .dc-legend-item')
    .style('opacity', function(d, i) {
      var subchart = chart.select('g.sub._' + i);
      var visible = subchart.style('visibility') !== 'hidden';
        return visible ? 1 : 0.2;
    });
}

function legendToggle(chart) {
  chart.selectAll('g.dc-legend .dc-legend-item')
    .on('click.hideshow', function(d, i) {
      var subchart = chart.select('g.sub._' + i);
      var visible = subchart.style('visibility') !== 'hidden';
      subchart.style('visibility', function() {
        return visible ? 'hidden' : 'visible';
      });
      drawLegendToggles(chart);
    })
  drawLegendToggles(chart);
}

composite
  .on('pretransition.hideshow', legendToggle);

In addition, we'll set the legend item translucent to indicate that the item is hidden.

We want to do this for all items, instead of in response to the click event, because it's more reliable to separate actions from drawing, and draw based on data. In particular, this handles the case where something else (for example an external filtering or zooming event) causes the legend to redraw.



标签: dc.js