d3.js bar charts transitioning between multiple csv files

元气小坏坏 提交于 2019-12-06 15:13:11

In your update function, you're executing the same code as initially -- you need to take into account the existing elements here. The code should look something like this:

// update axes
svg.select(".x").call(xAxis);
svg.select(".y").call(yAxis);

// update bars
var sel = svg.selectAll(".bar").data(data);
// add new bars
sel.enter().append("rect")
  .attr("class", "bar");
// update existing (and new) bars
sel.attr("x", function(d) { return x(d.letter); })
  .attr("width", x.rangeBand())
  .attr("y", function(d) { return y(d.frequency); })
  .attr("height", function(d) { return height - y(d.frequency); })
  .on('mouseover', tip.show)
  .on('mouseout', tip.hide);
// remove bars no longer present
sel.exit().remove();

To make the change with a transition, add .transition() before the update of the attributes, e.g.

sel.transition()
  .attr("x", function(d) { return x(d.letter); })
  // etc
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!