简体   繁体   English

d3实时图形仅在延迟后出现

[英]d3 realtime graph appears only after a delay

I made a realtime graph for plotting a simple sine wave. 我制作了用于绘制简单正弦波的实时图形。 Basically, the code is only slightly modified from the Path Transitions d3 example at this link: http://bost.ocks.org/mike/path/ 基本上,该代码仅在以下链接的“路径转换d3”示例中进行了少量修改: http : //bost.ocks.org/mike/path/

My code is here: http://jsfiddle.net/bgzsmqmw/2/ 我的代码在这里: http : //jsfiddle.net/bgzsmqmw/2/

There is some weird behavior that I can't explain, however. 但是,有些奇怪的行为我无法解释。

If I create new realtime data with y-values produced by the random() function, then as the data is added and rolls on to the time-domain, it is displayed properly. 如果我使用random()函数产生的y值创建新的实时数据,则在添加数据并将其滚动到时域时,它会正确显示。

If I generate a sine wave with Math.sin(), however, the line does not display until after a significant delay, and then suddenly the whole line appears at once. 但是,如果我用Math.sin()生成一个正弦波,则该行直到出现明显的延迟后才显示,然后突然整行出现。 The only difference is the function that produces the new data point. 唯一的区别是产生新数据点的功能。

In the jsfiddle I linked, try using each of the two lines below the "// TRY THESE TWO LINES:" comment in turn. 在我链接的jsfiddle中,尝试依次使用“ //尝试这两行:”注释下面的两行。 This will produce the two cases of behavior I described. 这将产生我描述的两种情况。

Any idea what's going on? 知道发生了什么吗?

// TRY THESE TWO LINES:
//var sin = function(){return 0.2*Math.sin(theta);}; // Line only shows up after delay
var sin = function(){return random();}; // Line shows up immediately

This is because you're calling the function newData before assigning values to theta and dtheta. 这是因为要在将值分配给theta和dtheta之前调用newData函数。 So the first time this function is called, theta and dtheta are undefined (NaN), which makes the sin function return NaN. 因此,第一次调用此函数时,theta和dtheta是未定义的(NaN),这使sin函数返回NaN。 D3's line function creates an invalid SVG path when the x or y input value is NaN. 当x或y输入值为NaN时,D3的line函数将创建无效的SVG路径。 This continues to happen until the NaN value is "shifted to the left" out of the data array, which is why you don't see the line initially and when it appears, it does so all of a sudden. 这种情况一直持续发生,直到NaN值从数据数组“移到左侧”为止,这就是为什么您最初看不到该行并且当它出现时突然突然看到它的原因。

newData();

var theta = 0;
var dtheta = 1;

function newData()
{
    theta += dtheta;

    //var sin = function(){return 0.2*Math.sin(theta);};
    var sin = function(){return random();};

    data.push({x : new Date(), y : sin()});
};

To fix this, simply move the below two lines to the top before newData is ever called. 要解决此问题,只需在调用newData之前将下面两行移动到顶部。 See working fiddle here: http://jsfiddle.net/bgzsmqmw/4/ 在这里查看工作小提琴: http : //jsfiddle.net/bgzsmqmw/4/

var theta = 0;
var dtheta = 1;

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

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