[D3] Better Code Organization with selection.call() with D3 v4

本文介绍使用D3.js进行数据可视化的实践案例,通过创建条形图展示数据集,并运用交互式效果如放大、填充颜色变化及鼠标悬停提示等增强用户体验。

Most of D3’s native selection APIs also return the selection (or a new selection), to enable multiple method calls to be chained together. Since the code you write isn’t on the selection prototype, chaining your methods would take some extra work. selection.call() will call any function reference you give it, providing the selection as the first parameter, and then it returns the selection for you to ensure chaining is supported.

 

var scores = [
  { name: 'Alice', score: 96 },
  { name: 'Billy', score: 83 },
  { name: 'Cindy', score: 91 },
  { name: 'David', score: 96 },
  { name: 'Emily', score: 88 }
];

var bar = d3.select('.chart')
  .append('svg')
    .attr('width', 225)
    .attr('height', 300)
  .selectAll('g')
  .data(scores)
  .enter()
    .append('g')
    .attr('transform', (d, i) => 'translate(0, ' + i * 33 + ')');

function scaleBar (selection, scale) {
  selection.style('transform', 'scaleX(' + scale + ')');
}

function setFill (selection, color) {
  selection.style('fill', color);
}

function fade (selection, opacity) {
  selection.style('fill-opacity', opacity);
}

bar.append('rect')
    .style('width', d => d.score)
    .attr('class', 'bar')
    .on('mouseover', function (d, i, elements) {
      d3.select(this)
        .call(scaleBar, 2)
        .call(setFill, 'orange');

      d3.selectAll(elements)
        .filter(':not(:hover)')
        .call(fade, 0.5);
    })
    .on('mouseout', function (d, i, elements) {
      d3.select(this)
        .call(scaleBar, 1)
        .call(setFill, 'lightgreen');

      d3.selectAll(elements)
        .call(fade, 1);
    });

bar.append('text')
  .attr('y', 20)
  .text(function (d) {
    return d.name;
  });

 

转载于:https://www.cnblogs.com/Answer1215/p/7300518.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值