Update data sets and graphs

effect

Before update:
Insert picture description here

Updated:
Insert picture description here

example3-2.ftl page

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <script src="../js/d3.js"></script>
    <title>更新数据集和图形-示例3-2</title>
</head>
<body onload="makeDemo32()">

    <svg id="update"></svg>

</body>

<script>
    function makeDemo32() {
     
     
        // 数据集1。每个条目由x坐标和y坐标以及颜色组成。在绑定数据时,使用颜色字符串作为key值。
        var data1 = [[2, 3, "green"], [1, 2, "red"], [2, 1, "blue"], [3, 2, "yellow"]];
        // 数据集2。每个条目由x坐标和y坐标以及颜色组成。在绑定数据时,使用颜色字符串作为key值。
        var data2 = [[1, 1, "red"], [3, 3, "black"], [1, 3, "lime"], [3, 1, "blue"]];

        // 将数据值映射到比例尺上对应的屏幕坐标。
        var scX = d3.scaleLinear().domain([1, 3]).range([100, 200]),
            scY = d3.scaleLinear().domain([1, 3]).range([50, 100]);

        // 取得<svg>元素的句柄以复用
        var svg = d3.select("#update");

        // 为这个<svg>元素注册一个click事件处理程序。
        svg.on("click", function () {
     
     
            // 在用户单击时,将现有数据集和备用数据集进行切换。
            [data1, data2] = [data2, data1];
            // 以颜色名为key值,将新数据绑定到图中(现有)的<circle>元素。
            var circles = svg.selectAll("circle").data(data1, d => d[2]);
            // 删除那些不再有绑定数据的元素(exit()选择集)。
            circles.exit().remove();
            // 为数据集中的新数据点创建新元素(enter()选择集)。
            circles.enter().append("circle")
                .attr("r", 5).attr("fill", d => d[2])
                // 将之前选择集中保留的现存元素合并到新创建元素的选择集中,并将其视为之后的“当前”选择集。
                .merge(circles)
                // 使用绑定的数据值更新并和选择集中的所有元素进行合并。
                .attr("cx", d => scX(d[0])).attr("cy", d => scY(d[1]));
        });

        // 生成一个合成点击事件。触发事件处理程序,并在第一次加载页面时填充图形
        svg.dispatch("click");

    }
</script>
</html>

Ideas

Click the graph area to replace the current data set with another data set and update the corresponding graph

  1. Bind the new data to the existing element selection set.
  2. Delete any remaining items that are no longer associated with matching data (the selection set obtained by the exit() method).
  3. Create and configure all items related to data points that did not exist before (the selection set obtained by the enter() method).
  4. Combine the remaining items in the original selection set with the newly created items in the enter() selection set.
  5. Update all the combined selection sets based on the current value of the bound data set.

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

Guess you like

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