javascript - 为什么转换后旧条仍然可见

标签 javascript d3.js

我有一个包含 5 个条形的 D3 条形图。当我更新它时,我可以看到它过渡到正确的 3 个栏,但一些原始栏仍然可见 - 如何让它们退出?

这就是它最初的样子:

enter image description here

这就是它最终的样子:

enter image description here

深蓝色条是正确的。当前用于更新“rect”对象的代码如下:

var plot = d3.select("#barChartPlot")
  .datum(currentDatasetBarChart);

/* Note that here we only have to select the elements - no more appending! */

plot.selectAll("rect")
  .data(currentDatasetBarChart)
  .transition()
  .duration(750)
  .attr("x", function (d, i) {
    return xScale(i);
  })
  .attr("width", width / currentDatasetBarChart.length - barPadding)
  .attr("y", function (d) {
    return yScale(+d.measure);
  })
  .attr("height", function (d) {
    return height - yScale(+d.measure);
  })
  .attr("fill", colorChosen);

最佳答案

您只有 3 个新柱,因此数据中的元素数量已发生变化。 您需要使用 update pattern .

var rects = plot.selectAll("rect")
  .data(currentDatasetBarChart);

  rects.enter()
   .append("rect")
    //Code to style and define new rectangles.

  //Update 
  rects.update()
  .transition()
  .duration(750)
  .attr("x", function (d, i) {
    return xScale(i);
  })
  .attr("width", width / currentDatasetBarChart.length - barPadding)
  .attr("y", function (d) {
    return yScale(+d.measure);
  })
  .attr("height", function (d) {
    return height - yScale(+d.measure);
  })
  .attr("fill", colorChosen);

  // Remove unused rects
  rects.exit().remove();

关于javascript - 为什么转换后旧条仍然可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39922120/

相关文章:

javascript - 如何在 arc.centroid() 上向 D3 和弦图 Group Arcs 添加标签?

javascript - 为什么当我告诉 AngularJS $scope.watch() 观察数组时它停止工作?

javascript - 选择第一个选择框值后填充第二个选择框,如何在脚本中选择要编辑的值

javascript - jsfiddle : not able to add script with http

html - 在 D3 中鼠标悬停时突出显示表格的列的最有效方法是什么?

javascript - D3.JS yScale 仅针对一个值返回 "undefined"

javascript - 嵌套for循环,有更好的方法吗?

javascript - 如何在不执行操作的情况下从下拉列表中存储值以在其他 php 页面中使用

javascript - 如何向 d3.js 折线图添加额外范围

javascript - 给定 X 文件数组绘制 X 图表 + 使用数组 + d3 中的元素添加图表标题