Post

d3js Bar Chart Updator With exit Animation

The key function in selection.data([data, key]) is for .join().

In conjunction with selection.join (or more explicitly with selection.enter, selection.exit, selection.append and selection.remove), selection.data can be used to enter, update and exit elements to match data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
function drawChart(data) {
  const margins = {'width': 120, 'height': 200};

  let svg = d3.select('#chart')
    .append('svg')
    .attr('width', margins.width)
    .attr('height', margins.height);

  var xScale = d3.scaleBand()
    .domain([...Array(4).keys()])
    .range([0, 100])
    .padding(0.2);

  var yScale = d3.scaleLinear()
      .domain([0, 10])
    .range([0, 180]);

  let bar = svg
    .selectAll('rect');

  return (data) => {
    const t = svg.transition().duration(750);

    bar = bar.data(data, d => d)
      .join(
        enter => enter.append('rect')
          .attr('x', 0 - xScale(1))
          .attr('y', (d) => 200 - yScale(d))
          .attr('height', d => yScale(d))
          .attr('width', xScale.bandwidth()),
        update => update,
        exit => exit
          .call(bar => bar.transition(t).remove()
                .attr('x', margins.width))
      )
      .call(bar => bar.transition(t)
          .attr('x', (_, i) => xScale(i))
          .attr('y', (d) => {
            console.log(d);
            return 200 - yScale(d)
          })
          .attr('height', d => yScale(d))
          .attr('width', xScale.bandwidth())
          .attr('fill', '#008765')
      );
  }
}

var chart = drawChart();

function getRandomData() {
  const result = [];
  for(i = 0; i < 4; i ++) {
    const obj = {};
    obj.a = Math.floor(Math.random() * 10);
    // result.push(obj);
    result.push(Math.floor(Math.random() * 10));
  }
  return result;
}

document.querySelector('#updateBtn').addEventListener('click', function() {
  chart(getRandomData());
});

This post is licensed under CC BY 4.0 by the author.