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
    .attr('height', d => barScale(d))
    .attr('width', barWidth - 1);

After adding the animation effect, the code is as follows

    .attr('height', 0) //State before animation starts
    .attr('width', barWidth - 1)
    .transition() //selection.transition() returns transition
    .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

    .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
    .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()
    .attr('height', 0)
    .attr('width', barWidth - 1)
    .attr('y', d => barScale(d))
    .transition(t) //Use the newly defined transition
    .attr('height', d => barScale(d))
    .attr('y', 0);

Same effect


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

Keywords: Javascript Attribute

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