2013-06-27 88 views
0

我用javascript和d3.js實現了一個實時圖。數據是隨機生成的,並基於隨機數發生變化。我想填充折線圖下方的區域,但我不知道如何填充數據,因爲數據正在移動!下面的代碼是靜態的圖表正確的,但我怎麼可以用它來動態移動數據實時圖的區域填充

//Css part 
.area { 
fill: lightsteelblue; 
stroke-width: 0; 
} 
//script 
var area = d3.svg.area() 
.x(function(d, i) { return x(i); }) 
.y0(height) 
.y1(function(d, i) { return y(d); }); 

svg.append("path") 
.datum(data) 
.attr("class", "area") 
.attr("d", area); 

這就是我的數據是如何產生的:

var n = 100, 
    random = d3.random.normal(0, 50), 
    data = d3.range(n).map(random); 

感謝,

回答

1

爲了實時移動該區域,您將不得不做相當多的工作。幸運的是,Mike Bostock用d3.js爲path transitions寫了一篇很好的教程。

關鍵代碼:

// push a new data point onto the back 
data.push(random()); 

// redraw the line, and then slide it to the left 
path 
    .attr("d", area) 
    .attr("transform", null) 
    .transition() 
    .ease("linear") 
    .attr("transform", "translate(" + x(-1) + ")"); 
// pop the old data point off the front 
data.shift(); 

另外請注意,你一定會擁有在一個點使用的選擇,這樣做,你可以看看下面的教程:A Bar Chart, Part 2

除此之外,你已經使用的面積圖的例子,你幾乎完成!唯一的區別是,你寫

現在,你也可以從下面的問題中得到啓示:Smooth update to x axis in a D3 line chart?

最後,here is a jsFiddle,爲您提供你在找什麼工作的例子。

+0

非常感謝您的幫助! :) – star