2016-06-19 216 views
0

如何以1秒的间隔重复执行此代码?这个想法是更新d3.js折线图并移动(平滑)图表的y轴上的点。d3.js折线图 - 更新积分值

用随机数据添加一行:

var randomNumber = Math.floor(Math.random() * 6) + 1;  

    data = [ 
     [{'x':0,'y':0},{'x':5,'y':0},{'x':10,'y':0},{'x':15,'y':3},{'x':20,'y':7},{'x':25,'y': randomNumber}] 
    ];  

    var path = svg.selectAll('.d3-line') 
     .data(data) 
     .enter() 
     .append("path") 
      .attr("d", line) 
      .attr("class", "d3-line d3-line-medium") 
      .style('stroke-width', 3) 
      .style('stroke', function(d,i){  
       return colors[i%colors.length]; 
      }); 

添加行的要点:

// Group dots 
    var points = svg.selectAll('.d3-dots') 
     .data(data) 
     .enter() 
     .append("g") 
      .attr("class", "d3-dots"); 


    // Add dots 
    points.selectAll('.d3-dot') 
     .data(function(d, index) {  
      var a = []; 
      d.forEach(function(point,i) { 
       a.push({'index': index, 'point': point}); 
      }); 
      return a; 
     }) 
     .enter() 
     .append('circle') 
      .attr('class', 'd3-dot') 
      .attr("r", 0) 
      .attr("transform", function(d) { 
       return "translate(" + x(d.point.x) + "," + y(d.point.y) + ")"; } 
      ) 
      .style("fill", "#fff") 
      .style("stroke-width", 0) 
      .style('stroke', function(d,i){ 
       return colors[d.index%colors.length]; 
      }) 
      .style("cursor", "pointer"); 

问候,

回答

0

添加到您的代码给line chart a smooth transition

First add an id to the line as stated below:

var path = svg.selectAll('.d3-line') 
     .data(data) 
     .enter() 
     .append("path") 
      .attr("id", function(d,i){ return "line"+i;}) 
      .attr("d", line) 
      .attr("class", "d3-line d3-line-medium") 
      .style('stroke-width', 3) 
      .style('stroke', function(d,i){  
       return colors[i%colors.length]; 
      }); 

Following the above code add this below snippet:

d3.selectAll(".line").each(function(d,i){ 

        // Get the length of each line in turn 
        var totalLength = d3.select("#line"+i).node().getTotalLength(); 
         d3.select("#line"+i).attr("stroke-dasharray", totalLength + " " + totalLength) 
          .attr("stroke-dashoffset", totalLength) 
          .transition() 
          .duration(2000) 
          .delay(100*i) 
          .ease("linear") //linear, quad, bounce... other examples here - http://bl.ocks.org/hunzy/9929724 
          .attr("stroke-dashoffset", 0); 
         // .style("stroke-width",3) 
        }); 
+0

我这样做,你说的,并保持不工作。我替换了代码,没有任何东西! 我的理念是在y轴上移动平滑点。 折线图:oi68.tinypic.com/344eebm.jpg –

+0

你想让我的所有源代码分析吗?对不起坚持,但这是为大学工作 –

+0

它肯定会工作。请注意看看这个例子,我使用了与transition相同的方法(http://jsbin.com/baqaki/edit?js,output)。 – SiddP