d3.js甜甜圈图::其他路径被渲染而不更新

d3.js doughnut chart :: Additional paths are rendered and not updated

本文关键字:更新 路径 js 甜甜圈 其他 d3      更新时间:2023-09-26

我在d3中渲染甜甜圈图时遇到问题。我有两个甜甜圈,我正在为每个函数并排创建:

         data.forEach(function(d,i){...}

图表渲染得很好。当我去更新图表时,路径会被重新绘制。不确定为什么会发生这种情况,因为我正在使用.enter()

有什么建议吗?

        var singleDonutData = [1];
        var donutSections=singleDonut.selectAll(".donutSections")
            .data(singleDonutData)
            .enter()
            .append("g")
            .attr("class","donutSections");
        var pathGroup = svg.select("." + donutName).select(".donutSections").selectAll("path.arc")
            .data(pie(d));
        var path = pathGroup
            .enter()
            .append('path')
            .style('fill', function(d){   //give arc a color in SVG Scale
                return color(d.data.label);
            })
            .attr("d", arc)
            .each(function(d) { this._current = d; }); // store the initial angles;

您需要在生成的路径上添加相应的类名,例如:

var pathGroup = svg.select("." + donutName).select(".donutSections").selectAll("path.arc")
        .data(pie(d));
    var path = pathGroup
        .enter()
        .append('path')
        .style('fill', function(d){  
            return color(d.data.label);
        })
        .attr("class", "arc") // corresponding to selectAll("path.arc")
        .attr("d", arc)
        .each(function(d) { this._current = d; }); angles;

以便在更新图表时,d3可以正确地选择这些已经渲染的路径。

更新后,您还需要添加代码来处理更新选择。类似这样的东西:

pathGroup.transition().duration(1000)
.attrTween("d", function(d){
   // some transition animation code here if you need it.
})