更新饼图更新的文本位置

updating text position on pie chart update

我一直在尝试将此 design 改编成动态饼图。

除了让文本在更新时重新定位之外,一切都进行得相当顺利。

在下面的示例中,我首先删除文本标签然后重新绘制,我认为这不是最好的方法,我试图用下面注释掉的代码来处理它但一直没有成功。

Plunk

违规代码;

function updatePath() {

    g = svg.datum(donutData).selectAll(".arc")
      .data(pie)
    g.select("path")
      .transition()
      .duration(750)
      .attrTween("d", arcTween) // redraw the arcs

    svg.selectAll(".donutText").remove()

    pieTextLabel()

}

// Attempt 1 Below

    /*  

        svg.selectAll(".donutText")
        .style("opacity", 0)
          .attr("dy", 18)
          .append("textPath")
          .attr("startOffset", "50%")
          .style("text-anchor", "middle")
          .attr("xlink:href", function(d, i) {
            return "#donutArc" + i;
          })
          .text(function(d) {
            return d.value;
          })
          .transition()
          .duration(1000)
          .style("opacity", 1);

      */


  function pieTextLabel() {
    var selectText = svg.selectAll(".donutText")
      .data(donutData)

    selectText
      .enter().append("text")
      .attr("class", "donutText")
      .attr("dy", 18)
      .append("textPath")
      .attr("startOffset", "50%")
      .style("text-anchor", "middle")
      .attr("xlink:href", function(d, i) {
        return "#donutArc" + i;
      })
      .text(function(d) {
        return d.value;
      });

    selectText.exit().remove()

  }

  function drawPie() {
    var g = svg.selectAll(".donutArcSlices")
      .data(pie(donutData))
      .enter().append("g")
      .attr("class", "arc");

    var path = g.append("path")
      .attr("d", arc)
      .style("fill", function(d) {
        return color(d.data.label);
      })
      .each(function(d, i) {
        this._current = d;

        var firstArcSection = /(^.+?)L/;
        var newArc = firstArcSection.exec(d3.select(this).attr("d"))[1];
        newArc = newArc.replace(/,/g, " ");

        svg.append("path")
          .attr("class", "hiddenDonutArcs")
          .attr("id", "donutArc" + i)
          .attr("d", newArc)
          .style("fill", "none");
      })

  }

无法破解 - 非常感谢 help/advice!

谢谢

因为你没有更新 path

先删除旧的path

svg.selectAll("path").remove()

然后重新创建它

var path = g.append("path")
  .attr("d", arc)
  .style("fill", function(d) {
    return color(d.data.label);
  })
  .each(function(d, i) {
    this._current = d;

    var firstArcSection = /(^.+?)L/;
    var newArc = firstArcSection.exec(d3.select(this).attr("d"))[1];
    newArc = newArc.replace(/,/g, " ");

    svg.append("path")
      .attr("class", "hiddenDonutArcs")
      .attr("id", "donutArc" + i)
      .attr("d", newArc)
      .style("fill", "none");
  })

http://plnkr.co/edit/WTuX38GCgIFLFfc1QPVv?p=preview