d3.js dynamic chart

d3js v5.9.2
Using D3 to create dynamic chart mainly uses the API of d3.tracing, through which you can complete the animation
My learning record is to learn about these API s through an example

Moving histogram

Take the previous example. Here is the code: Complete column chart

The modified code part is at the place of creating rect:

//Original code
barContainer.append('rect')
    .attr('height', d => barScale(d))
    .attr('width', barWidth - 1);

After adding the animation effect, the code is as follows

barContainer.append('rect')
    .attr('height', 0) //State before animation starts
    .attr('width', barWidth - 1)
    .transition() //selection.transition() returns transition
    .duration(1000)//Duration
    .ease(d3.easeBackInOut)//transition.ease(easing function), which is the animation function of d3, and many other APIs
    .attr('height', d => barScale(d));//transition.attr()

? It's drawn from top down
Here we can use the y attribute of rect to control the animation. y represents the vertical coordinate of the upper left corner of the rectangle

barContainer.append('rect')
    .attr('height', 0)
    .attr('width', barWidth - 1)
    .attr('y', d => barScale(d)) //y is relative to the g container of rect parent. The top starts from the bottom, so the value is set to the height of rectangle
    .transition()
    .duration(2000)
    .ease(d3.easeBackInOut)
    .attr('height', d => barScale(d))
    .attr('y', 0);//To top of g container

So the process is that the length of the rectangle stretches down and the position moves up


This completes the animation

More concise writing

The above method is the simplest one, but the code is too long or the same animation effect will be jumbled if used multiple times. We can get a custom transition through d3.transition()
Easy to use

//Define transition
let t = d3.transition()
    .duration(2000)
    .ease(d3.easeBackInOut);
barContainer.append('rect')
    .attr('height', 0)
    .attr('width', barWidth - 1)
    .attr('y', d => barScale(d))
    .transition(t) //Use the newly defined transition
    .ease(d3.easeBackInOut)
    .attr('height', d => barScale(d))
    .attr('y', 0);

Same effect

summary

d3 also provides other commonly used API s, such as ease(), duration(), delay(), etc
The code is here (d3 library is in build)

Reference material

Chapter 9 let the chart move
Introduction to SVG image: Ruan Yifeng
selection.transition()

Keywords: Javascript Attribute

Added by dmIllithid on Mon, 09 Dec 2019 13:05:35 +0200