使用d3.js移动折线图

Moving line timegraph with d3.js

本文关键字:折线图 移动 js d3 使用      更新时间:2023-09-26

我正在使用d3.js创建一个显示数据的图,该图在折线图中定期更新(每秒更新一次)。x轴(时间)和整个图形连续向左平移。

我试着以本教程为基础:http://bost.ocks.org/mike/path/

这个jsfiddle就是我到目前为止得到的:http://jsfiddle.net/panbert/dmynvjzx/

它有效。但在更新方法中(Javascript部分的最后一个方法)

//move the graph left
svg.selectAll(".line")
  .attr("d", line(data))
  .attr("transform", null)
  .transition()
  .duration(950)
  .ease("linear")
  .attr("transform", "translate(" + (x(0) - x(1000)) + ")");

我使用950毫秒的持续时间进行转换,将图形向左平移1秒。在教程中,转换的延迟是1秒,这对我来说更有意义。每秒钟,图形都会被一个翻译向左移动1秒,这个翻译的持续时间应该需要一秒钟。这听起来比950毫秒的翻译更有逻辑性。

如果我在第161行将jsfiddle中的翻译持续时间增加到1秒(就像教程中一样),我会出现图形错误,而且它不再像预期的那样工作。

有人能向我解释一下为什么?

原因是您在每1秒后调用更新函数

setInterval(update, 1000);

并且给出了过渡的持续时间

svg.selectAll(".line")
      .attr("d", line(data))
      .attr("transform", null)
      .transition()
      .duration(950)//this means that the transition will take 950 mili secs which is less than the update rate.

但是,当你像更新一样持续1秒时,它不会给你跳跃效果,因为过渡没有结束,你正在用新的值更新路径。

svg.selectAll(".line")
      .attr("d", line(data))
      .attr("transform", null)
      .transition()
      .duration(1000)//this means that the transition will take 1000 

所以最好的方法是,当你给持续时间1000(1秒)使更新速率略高于1秒,例如(1.1秒)

setInterval(update, 1100);

此处的工作代码

希望这能有所帮助!