javascript – 如何在更新d3.js图表​​之前干净地删除数据?

我是D3的新手,一直在努力解决所有问题.我正在尝试配置此示例
here以使用新数据进行更新并进行适当的转换.

这是我配置的代码笔(单击提交更新)
http://codepen.io/anon/pen/pbjLRW?editors=1010

从我可以收集的内容来看,使用.exit()的一些变体来进行干净的数据转换是必需的,但是在阅读了一些教程后,我仍然发现很难知道它是如何工作的.我已经看到了在调用绘图函数之前简单地删除容器的示例,但是在我有限的经验中,它会在更改数据时导致闪烁,所以我不确定它是否是最佳实践?

现在,我不确定为什么我的codepen中的数据没有正确更新,但我主要担心的是尝试正确转换.理想情况下,我想知道在更改数据时如何移动针,因此它将从90>例如,代替90> 0> 40.

但是,一旦在链接的codepen中单击提交,我肯定会解决为什么它不会在同一位置重绘自己的原因.

这是我的更新功能;

function updateGuage() {
  d3.selectAll("text").remove()
  d3.selectAll('.needle').remove()
  chart.remove()
  name = "qwerty";
  value = "25";
  drawGuage();
}

初步抽签;

function drawGuage() {
  percToDeg = function(perc) {
    return perc * 360;
  };

  percToRad = function(perc) {
    return degToRad(percToDeg(perc));
  };

  degToRad = function(deg) {
    return deg * Math.PI / 180;
  };

  // Create SVG element
  svg = el.append('svg').attr('width', width + margin.left + margin.right).attr('height', height + margin.top + margin.bottom);

  // Add layer for the panel
  chart = svg.append('g').attr('transform', "translate(" + ((width + margin.left) / 2) + ", " + ((height + margin.top) / 2) + ")");

  chart.append('path').attr('class', "arc chart-first");
  chart.append('path').attr('class', "arc chart-second");
  chart.append('path').attr('class', "arc chart-third");

  arc3 = d3.svg.arc().outerRadius(radius - chartInset).innerRadius(radius - chartInset - barWidth)
  arc2 = d3.svg.arc().outerRadius(radius - chartInset).innerRadius(radius - chartInset - barWidth)
  arc1 = d3.svg.arc().outerRadius(radius - chartInset).innerRadius(radius - chartInset - barWidth)

  repaintGauge = function() {
      perc = 0.5;
      var next_start = totalPercent;
      arcStartRad = percToRad(next_start);
      arcEndRad = arcStartRad + percToRad(perc / 3);
      next_start += perc / 3;

      arc1.startAngle(arcStartRad).endAngle(arcEndRad);

      arcStartRad = percToRad(next_start);
      arcEndRad = arcStartRad + percToRad(perc / 3);
      next_start += perc / 3;

      arc2.startAngle(arcStartRad + padRad).endAngle(arcEndRad);

      arcStartRad = percToRad(next_start);
      arcEndRad = arcStartRad + percToRad(perc / 3);

      arc3.startAngle(arcStartRad + padRad).endAngle(arcEndRad);

      chart.select(".chart-first").attr('d', arc1);
      chart.select(".chart-second").attr('d', arc2);
      chart.select(".chart-third").attr('d', arc3);

    }
    /////////

  var texts = svg.selectAll("text")
    .data(dataset)
    .enter();

  texts.append("text")
    .text(function() {
      return dataset[0].metric;
    })
    .attr('id', "Name")
    .attr('transform', "translate(" + ((width + margin.left) / 6) + ", " + ((height + margin.top) / 1.5) + ")")
    .attr("font-size", 25)
    .style("fill", "#000000");

  var trX = 180 - 210 * Math.cos(percToRad(percent / 2));
  var trY = 195 - 210 * Math.sin(percToRad(percent / 2));
  // (180, 195) are the coordinates of the center of the gauge.

  displayValue = function() {
    texts.append("text")
      .text(function() {
        return dataset[0].value;
      })
      .attr('id', "Value")
      .attr('transform', "translate(" + trX + ", " + trY + ")")
      .attr("font-size", 18)
      .style("fill", '#000000');
  }

  texts.append("text")
    .text(function() {
      return 0;
    })
    .attr('id', 'scale0')
    .attr('transform', "translate(" + ((width + margin.left) / 100) + ", " + ((height + margin.top) / 2) + ")")
    .attr("font-size", 15)
    .style("fill", "#000000");

  texts.append("text")
    .text(function() {
      return gaugeMaxValue / 2;
    })
    .attr('id', 'scale10')
    .attr('transform', "translate(" + ((width + margin.left) / 2.15) + ", " + ((height + margin.top) / 30) + ")")
    .attr("font-size", 15)
    .style("fill", "#000000");

  texts.append("text")
    .text(function() {
      return gaugeMaxValue;
    })
    .attr('id', 'scale20')
    .attr('transform', "translate(" + ((width + margin.left) / 1.03) + ", " + ((height + margin.top) / 2) + ")")
    .attr("font-size", 15)
    .style("fill", "#000000");

  var Needle = (function() {

    //Helper function that returns the `d` value for moving the needle
    var recalcPointerPos = function(perc) {
      var centerX, centerY, leftX, leftY, rightX, rightY, thetaRad, topX, topY;
      thetaRad = percToRad(perc / 2);
      centerX = 0;
      centerY = 0;
      topX = centerX - this.len * Math.cos(thetaRad);
      topY = centerY - this.len * Math.sin(thetaRad);
      leftX = centerX - this.radius * Math.cos(thetaRad - Math.PI / 2);
      leftY = centerY - this.radius * Math.sin(thetaRad - Math.PI / 2);
      rightX = centerX - this.radius * Math.cos(thetaRad + Math.PI / 2);
      rightY = centerY - this.radius * Math.sin(thetaRad + Math.PI / 2);

      return "M " + leftX + " " + leftY + " L " + topX + " " + topY + " L " + rightX + " " + rightY;

    };

    function Needle(el) {
      this.el = el;
      this.len = width / 2.5;
      this.radius = this.len / 8;
    }

    Needle.prototype.render = function() {
      this.el.append('circle').attr('class', 'needle-center').attr('cx', 0).attr('cy', 0).attr('r', this.radius);

      return this.el.append('path').attr('class', 'needle').attr('id', 'client-needle').attr('d', recalcPointerPos.call(this, 0));

    };

    Needle.prototype.moveTo = function(perc) {
      var self,
        oldValue = this.perc || 0;

      this.perc = perc;
      self = this;

      // Reset pointer position
      this.el.transition().delay(100).ease('quad').duration(200).select('.needle').tween('reset-progress', function() {
        return function(percentOfPercent) {
          var progress = (1 - percentOfPercent) * oldValue;

          repaintGauge(progress);
          return d3.select(this).attr('d', recalcPointerPos.call(self, progress));
        };
      });

      this.el.transition().delay(300).ease('bounce').duration(1500).select('.needle').tween('progress', function() {
        return function(percentOfPercent) {
          var progress = percentOfPercent * perc;

          repaintGauge(progress);
          return d3.select(this).attr('d', recalcPointerPos.call(self, progress));
        };
      });

    };

    return Needle;

  })();

  needle = new Needle(chart);
  needle.render();
  needle.moveTo(percent);

  setTimeout(displayValue, 1350);

}

任何帮助/建议非常感谢,

谢谢

最佳答案 你想看看的是
How selections work由迈克博斯托克写的.阅读本文后,围绕输入,更新和退出选择的所有内容都将变得更加清晰.

简而言之:

>使用selectAll(‘li’)创建元素选择
>通过调用数据([…])将选择与数据数组连接起来
>现在D3将已经在DOM中的内容与已加入的数据进行比较.以这种方式处理的每个DOM元素都有一个__data__属性,允许D3将数据项绑定到一个元素.
>加入数据后,通过调用enter()接收输入选择.这是尚未绑定到所选DOM元素的每个数据元素.通常,您使用输入选择来创建新元素,例如通过追加()
>通过调用exit(),您将收到退出选择.这些都是已存在的DOM元素,在连接后不再具有关联的数据项.通常使用exit选项删除带有remove()的DOM元素
>所谓的更新选择是在使用data()加入选择后返回的一件事.您需要将更新选择存储在变量中,因此即使在调用enter()或exit()之后也可以访问它.

注意d3v3和d3v4之间的区别:

在d3v3中,当您已经通过输入选择添加元素时,更新选择也包括那些新创建的DOM元素.在创建新元素后,知道更新选择会发生变化至关重要.

但是,使用d3v4时不再适用.更改日志说

“In addition, selection.append no longer merges entering nodes into the update selection; use selection.merge to combine enter and update after a data join.”

点赞