简体   繁体   中英

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/

My code is here: 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.

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. 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. 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. So the first time this function is called, theta and dtheta are undefined (NaN), which makes the sin function return NaN. D3's line function creates an invalid SVG path when the x or y input value is NaN. 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.

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. See working fiddle here: http://jsfiddle.net/bgzsmqmw/4/

var theta = 0;
var dtheta = 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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