D3过渡线发生两次

时间:2017-02-09 23:20:59

标签: javascript d3.js

我是D3的新手,我试图根据这里的一个片段松散地制作一个简单的实时图表:https://bost.ocks.org/mike/path/

我希望能够在移动的实时图表中添加一些行,并从Web套接字更新它们(我知道该怎么做!!)

当我尝试添加第二行时,图表不能平滑更新,我认为转换被调用两次。任何帮助都感激不尽。

下面的代码,但这里是一个小提琴https://jsfiddle.net/q8qgbj58/

D = [{'apple': 2, 'meizu': 12, 'samsung': 9, 'oppo': 12, 'foo': 42, 'bar': 42}, 
     {'apple': 91, 'meizu': 22, 'samsung': 72, 'foo': 'test', 'bar': "blub"}]

for d in D:
    print(eval(code)) # prints True, False

1 个答案:

答案 0 :(得分:2)

看起来问题是在一行调用" tick"时更新所有行的数据。您会注意到您的示例在1行中正常工作,并且在3行中更加生涩。这是因为函数tick中的for循环。 D3中的数据绑定非常有用,但需要一些时间才能习惯使用。我做的两个主要代码更改是使line()成为变量并从tick函数中删除for循环。一个更新的小提琴(我试图只是注释掉原始代码,因此您可以轻松地看到差异):https://jsfiddle.net/s07d2hs3/

var line = d3.line()
   .curve(d3.curveBasis)
   .x(function(d, i) { return x(now - (n - 1 - i) * duration); })
   .y(function(d, i) { return y(d); });

function tick() {
    var index;
    var i;
   // Push a new data point onto the back.
   this.__data__.push(random());
   // Redraw the line.
   d3.select(this)
      .attr("d", line)
      .attr("transform", null);

   // Pop the old data point off the front.
      this.__data__.shift();

    now = new Date();
    x.domain([now - (n - 2) * duration, now - duration]);
    axis.transition()
        .duration(duration)
        .ease(d3.easeLinear)
        .call(d3.axisBottom(x));

    // Slide it to the left.
    d3.active(this)
      .attr("transform", "translate(" + x(now - (n - 1) * duration) + ")")
    .transition()
      .on("start", tick);
}

清理小提琴:https://jsfiddle.net/Lr5dxgr0/2/