The Old County The Old County - 3 months ago 16
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.

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

This is the jsfiddle that I've made to start creating this chart.
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 */
}

Answer

One solution that you can do is to append svg circles that correspond with the path before drawing the path. Example Fiddle: 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');
Comments