0

我正在尝试使用javascript和在网页上显示图表D3js

我已经按照http://bost.ocks.org/mike/path/中的示例开始并扩展了那里显示的图表的功能。

但是,在尝试使用转换来平滑更新我的图表时,我遇到了一些问题。

这是我的更新函数的代码,带有一些额外的注释

updateChart= function(){  

            //generate a new point, integer [0 5]
    var newPoint=Math.floor(Math.random() * 5);

    data.push(newPoint);

    // redraw the line
    path
    .attr("d", line)
    .attr("transform", null);

    //update x domain for axis labels - 
    //the new domain is the same as before slided by 1 position
    xDomain=[(xDomain[0]+1),(xDomain[1]+1)];
    xScale.domain(xDomain);

    //slide xAxis       
    svg.select(".x.axis")
    .transition()
    .duration(500)
    .call(xAxis);     //xAxis is my scale function and works fine for labels and data display

    //slide the line to the left  
    path
    .transition()
    .duration(500)
    .ease("linear")
    .attr("transform", "translate(" + xScale(xDomain[0]) + ")");

    // pop the old data point off the front
    data.shift();

};

我的问题是,虽然轴标签正确地向左滑动一个位置并在 0.5 秒内顺利完成,但该线立即“跳转”到更新的位置,并且不像教程中那样平滑过渡。

当我更新 y 轴范围时,也会发生类似的事情。轴平滑变化,而新线立即跳转到新刻度。

更新:这里是 jsfiddle 的链接:[已删除,没有足够的声誉。这与版本 6 的更新 2 的 jsfiddle 相同]

更新 2请在此处找到 jsfiddle 中的工作代码,其中还包括 y 轴刻度的变化。还要注意 y 轴刻度的变化如何在显示的数据中产生 1 个位置的偏移。我也将不胜感激有关此行为的任何意见。谢谢![已删除,声望不够。这与版本 8 的更新 2 的 jsfiddle 相同]

解决了

经过几个小时的尝试和阅读其他示例后,我已经能够解决问题

  • 关于沿 x 轴的过渡,问题出在过渡参数中,我应该输入 xScale(xDomain[0]-1) 而不是之前的 xScale(xDomain[0])

  • 关于不同比例之间的转换,问题出在我更新 yScale 之前应该发生的线的第一次重绘。通过移动线条

    path
    .attr("d",line)
    .attr("transform", null);
    

以上

    yScale.domain(yDomain); 

过渡顺利进行。

希望这会为其他人节省一些时间。在这里你可以找到工作代码 http://jsfiddle.net/4Z2FY/10/

正如ChrisJamesC所问,这里是更新y轴范围的相关代码

updateRange= function(newDomain){
//update domain
    yDomain=newDomain;

//redraw line BEFORE changing the yScale function 
    path
    .attr("d",line)
    .attr("transform", null);

    //change scale
    yScale.domain(yDomain); 

    //switch to new scale
    svg.select(".y.axis")
    .transition()
    .duration(750)
    .call(yAxis);

    // update the line
    path
    .transition()
    .duration(750)
    .attr("d", line)
    .attr("transform", null);    
}
4

0 回答 0