2016-08-28 122 views
0

Line chart growthD3折线图动画左至右

我有兴趣创建一个折线图 - 绘制本身从左至右 - 在x轴基本连接点。

http://bl.ocks.org/markmarkoh/8700606 http://bl.ocks.org/duopixel/4063326

这是我做了,开始创建这个图表的jsfiddle。 http://jsfiddle.net/NYEaX/1512/

//__invoke line 
$('[data-role="line"]').each(function(index) { 
    createLine(this); 
}); 



function createLine(el){ 
    var w = $(el).data("width"); 
    var h = $(el).data("height"); 

    var svg = d3.select($(el)[0]) 
     .append("svg") 
     .attr("width", w) 
     .attr("height", h); 

    var data = d3.range(11).map(function(){return Math.random()*10}) 
    var x = d3.scale.linear().domain([0, 10]).range([0, 700]); 
    var y = d3.scale.linear().domain([0, 10]).range([10, 290]); 
    var line = d3.svg.line() 
     .interpolate("cardinal") 
     .x(function(d,i) {return x(i);}) 
     .y(function(d) {return y(d);}) 

    var path = svg.append("path") 
     .attr("d", line(data)) 
     .attr("stroke", "steelblue") 
     .attr("stroke-width", "2") 
     .attr("fill", "none"); 

    var totalLength = path.node().getTotalLength(); 

    path 
     .attr("stroke-dasharray", totalLength + " " + totalLength) 
     .attr("stroke-dashoffset", totalLength) 
     .transition() 
     .duration(2000) 
     .ease("linear") 
     .attr("stroke-dashoffset", 0); 

    svg.on("click", function(){ 
     path  
     .transition() 
     .duration(2000) 
     .ease("linear") 
     .attr("stroke-dashoffset", totalLength); 
    }); 



    /* plot axis */ 
    var padding = 100; // space around the chart, not including labels 

    // define the x axis 
    var xAxis = d3.svg.axis() 
     .orient("bottom") 
     .scale(x); 
     //.tickFormat(date_format); 

    // draw x axis with labels and move to the bottom of the chart area 
     svg.append("g") 
      .attr("class", "xaxis axis") // two classes, one for css formatting, one for selection below 
      .attr("transform", "translate(0," + (h - padding) + ")") 
      .call(xAxis); 

    /* plot axis */ 
} 

回答

2

一个解决方案,你可以做的是追加一条绘制路径之前与路径对应SVG圈。例如小提琴:http://jsfiddle.net/stancheta/ystymLm4/6/

var circles = svg.selectAll("dot") 
     .data(data) 
     .enter().append("svg:circle") 
     .attr('class', 'circ') 
     .attr("r", 3) 
     .attr("cx", function(d, i) { return x(i); }) 
     .attr("cy", function(d, i) { return y(d); }) 
     .style('fill', 'lightsteelblue'); 
+0

是的,这就是好男人 - 我会怎么收拾轴 - 去除黑线基本上是 - 我不知道还如何与日期范围创建一些假的JSON数据如果确实要将x尺度调整到一个时间尺度? –

+0

如果你想改变最小的代码量,我已经更新了小提琴以模仿上面的图像:http://jsfiddle.net/stancheta/ystymLm4/7/并放入一些评论来解释我改变了什么。让我知道他们是否不清楚。 –

+0

这看起来不错的男人 - 有一个赏金,如果你想帮助解决这个部分--- http://stackoverflow.com/questions/39156400/d3-animating-a-bubble-chart-within-a-given-半径/ 39197206#39197206 –