dc.js composite chart toggle chart

≯℡__Kan透↙ 提交于 2019-12-04 13:40:23

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!