Update the chart with new data

effect

  • Picture before update
    Insert picture description here
  • Click the operation, the updated picture
    Insert picture description here

example3-1.ftl page

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <script src="../js/d3.js"></script>
    <title>使用新数据更新图表-示例3-1</title>
</head>
<body onload="makeDemo31()">

    <svg id="key"></svg>

</body>

<script>
    function makeDemo31() {
    
    
        // 原始数据集。
        var oldData = [["A",1], ["B",4], ["C",2]];
        // 新数据集。
        var newData = [["C",5], ["B",3]];

        var scX = d3.scaleLinear().domain([0,6]).range([50, 300]),
            scY = d3.scaleLinear().domain([0,3]).range([50, 150]);

        // 用整数以追踪文本标签和圆形的垂直位置。
        var j = -1, k = -1;

        // 将<svg>元素作为选择集,赋值给一个变量以便后续使用。
        var svg = d3.select("#key");

        // 创建文本标签。
        svg.selectAll("text")
            .data(oldData).enter().append("text")
            .attr("x", 20).attr("y", d => scY(++j)).text(d => d[0]);

        // 确定圆形的初始位置。
        svg.selectAll("circle").data(oldData).enter().append("circle")
            .attr("r", 5).attr("fill", "red")
            .attr("cx", d => scX(d[1])).attr("cy", d => scY(++k) - 5);

        svg.on("click", function () {
    
    
            // 在click事件处理程序中,新的数据集绑定到圆圈元素的选择集。data()函数的第二个参数定义了数据项之上的key值。
            var circles = svg.selectAll("circle").data(newData, d => d[0]);
            // 运用平滑过渡将数据点从旧的位置过渡到新的位置。
            circles.transition().duration(1000).attr("cx", d => scX(d[1]));
            // exit()选择集现在将A这个未匹配节点换一种颜色进行填充,从而对之前调用data()时没有绑定到该节点的数据点突出显示
            circles.exit().attr("fill", "blue");
        })

    }
</script>
</html>

Source address: https://github.com/lee58/d3/tree/master

Guess you like

Origin blog.csdn.net/qq_37335220/article/details/112298929