The Old County The Old County - 1 year ago 58
Javascript Question

d3 Line Chart animations from left to right

Line chart growth

I am interested to create a line chart -- that draws itself from left to right -- essentially connecting dots in the x-axis.

This is the jsfiddle that I've made to start creating this chart.

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

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

var svg =$(el)[0])
.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()
.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();

.attr("stroke-dasharray", totalLength + " " + totalLength)
.attr("stroke-dashoffset", totalLength)
.attr("stroke-dashoffset", 0);

svg.on("click", function(){
.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()

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

/* plot axis */

Answer Source

One solution that you can do is to append svg circles that correspond with the path before drawing the path. Example Fiddle:

    var circles = svg.selectAll("dot")
      .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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download