2017-07-07 100 views
0

我有一個滾動折線圖,隨着數據的進入實時更新。下面是折線圖的js小提琴。 https://jsfiddle.net/eLu98a6L/D3將點添加到動態折線圖

我想要做的就是用點圖替換這條線,所以每一個進來的點都會創建一個點,並且滾動功能被保留。這是我想要創建的圖表類型dow jones dot graph並最終我想刪除下面的行。

這是我用來嘗試添加點到我的圖形的代碼。

g.append("g") 
.selectAll("dot") 
.data(4) 
.enter("circle") 
.attr("cx", "2") 
.attr("cy", "2"); 

到目前爲止我還沒有成功。我對d3很陌生,所以任何幫助表示讚賞。謝謝!

回答

1

基於您的代碼這種做法可以是:

var circleArea = g.append('g'); /* added this to hold all dots in a group */ 
function tick() { 

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

    /* hide the line as you don't need it any more 
    d3.select(this) 
     .attr("d", line) 
     .attr("transform", null); 
    */ 

    circleArea.selectAll('circle').remove(); // this makes sure your out of box dots will be remove. 

    /* this add dots based on data */ 
    circleArea.selectAll('circle') 
    .data(data) 
    .enter() 
     .append('circle') 
     .attr('r',3) // radius of dots 
     .attr('fill','black') // color of dots 
     .attr('transform',function(d,i){ return 'translate('+x(i)+','+y(d)+')';}); 

    /* here we can animate dots to translate to left for 500ms */ 
    circleArea.selectAll('circle').transition().duration(500) 
    .ease(d3.easeLinear) 
    .attr('transform',function(d,i){ 
     if(x(i)<=0) { // this makes sure dots are remove on x=0 
       d3.select(this).remove(); 
     } 
     return 'translate('+x(i-1)+','+y(d)+')'; 
    }); 

    /* here is rest of your code */ 
    // Slide it to the left. 
    d3.active(this) 
     .attr("transform", "translate(" + x(-1) + ",0)") 
     .transition() 
     .on("start", tick); 
    // Pop the old data point off the front. 
    data.shift(); 
} 

看到它在行動:https://codepen.io/FaridNaderi/pen/weERBj

希望它能幫助:)

+0

這是偉大的,謝謝!您是否也碰巧知道如何在當前時間實現滾動xAxis,類似於本頁第三張圖中的那個? https://bost.ocks.org/mike/path/ – user2012813