d3从左到右的折线图动画

时间:2016-08-28 23:09:47

标签: javascript d3.js

Line chart growth

我有兴趣创建一个折线图 - 从左到右绘制自己 - 基本上连接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 */
}

1 个答案:

答案 0 :(得分: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');