简体   繁体   English

D3 v4更新条形图不绘制最后一个条形图

[英]D3 v4 Update Bar Graph Does Not Plot Last Bar

I am new to D3 and javascript is not my first language, so I'll apologize in advance for probably not using the best js practices. 我是D3的新手,而javascript不是我的母语,因此对于可能未使用最佳js做法的情况,我会提前道歉。

I am attempting to recreate this bar graph that will cycle through a dataset, adding in bars each time; 我试图重新创建此条形图,该条形图将遍历数据集,每次都添加条形图; but trying to modify it to be in D3 v4. 但尝试将其修改为D3 v4。

https://bl.ocks.org/RandomEtc/cff3610e7dd47bef2d01 https://bl.ocks.org/RandomEtc/cff3610e7dd47bef2d01

I've got it mostly working except it would plot the last bar graph. 除了可以绘制最后一个条形图之外,我基本上都能正常工作。 It will make a spot for it on the x-axis; 它将在x轴上为其定位; but no bar graph appears. 但没有条形图出现。

在此处输入图片说明

https://jsfiddle.net/jimdholland/07p8z8pb/35/ https://jsfiddle.net/jimdholland/07p8z8pb/35/

From what I can see, my iteration function is grabbing the last element and the data values. 从我可以看到,我的迭代函数正在获取最后一个元素和数据值。

function cycler(data) {
    var slices = [];
  for (var i = 0; i < data.length; i++) {
    slices.push(data.slice(0, i+1));
  } //End for loop
  slices.forEach(function(slice, index){
    setTimeout(function(){
        drawChart(slice);
      console.log(slice);
    }, index * 300);
  }); //End for Each
};  // End cycler function

I created a function that draws the graph and I assume it maybe with me not properly clearing out the old data. 我创建了一个绘制图形的函数,并且我认为可能是因为我没有正确清除旧数据。

function drawChart(data) {
  x.domain(data.map(function(d) { return d.Word; }));
  y.domain([0, d3.max(data, function(d) { return d.Positive; })]);

  svg.select(".xAxis").transition().duration(300).call(d3.axisBottom(x));
  svg.select(".yAxis").transition().duration(300).call(d3.axisLeft(y));

  //svg.select('.xaxis').transition().duration(300).call(xAxis);
  var bar = svg.selectAll("rect").data(data);

  bar.exit()
    .transition()
    .duration(300)
    .attr("y", innerHeight)
    .attr("height", 0)
    .style('fill-opacity', 1e-6)
    .remove();

  bar.enter().append("rect")
    .attr("class", "bar")
    .merge(bar)
    .attr("y", innerHeight)
    .attr("height", 0);

  bar.transition().duration(300)
    .attr("x", function(d) {return x(d.Word); })
    .attr("width", x.bandwidth())
    .attr("y", function(d) {return y(d.Positive); })
    .attr("height", function(d) {return height - y(d.Positive); });

};

Thanks for any help and I'm also open to better practices for writing my D3 code. 感谢您的帮助,我也愿意接受更好的做法来编写D3代码。

Inside your cycler() function you just need to change the for loop < to <= cycler()函数内部,您只需要将for循环<更改为<=

for (var i = 0; i <= data.length; i++) {
    slices.push(data.slice(0, i+1));
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM