Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Staggered transition in multi line graph

I'm new here and to d3.js/JavaScript in general. I would like to add a transition to a multi line graph so that each line (and associated label) is 'drawn' one after the other. I've managed to get this to work for the first line (and to a lesser extent all lines at the same time) but am struggling to see how I can stagger the transitions. I've tried using a for loop and .each() to call the transition via a function but haven't really got anywhere with either approach. Any help would be gratefully received. Relevant part of the code below. Thanks.

var country = svg.selectAll(".country")
    .data(countries)
  .enter().append("g")
    .attr("class", "country");

var path = country.append("path")
    .attr("class", "line")
    .attr("d", function(d) { return line(d.values); })
    .style("stroke", function(d) { return color(d.country); })

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

d3.select(".line")
    .attr("stroke-dasharray", totalLength + " " + totalLength)
    .attr("stroke-dashoffset", totalLength)
  .transition()
    .duration(1000)
    .ease("linear")
    .attr("stroke-dashoffset", 0)
    .each("end", function() {
        d3.select(".label")
          .transition()
            .style("opacity", 1);
        });

var labels = country.append("text")
    .datum(function(d) { return {country: d.country, value: d.values[d.values.length - 1]}; })
    .attr("class", "label")
    .attr("transform", function(d) { return "translate(" + x(d.value.month) + "," + y(d.value.rainfall) + ")"; })
    .attr("x", 3)
    .attr("dy", ".35em")
    .style("opacity", 0)
    .text(function(d) { return d.country; });
like image 731
user3194692 Avatar asked Oct 01 '22 21:10

user3194692


1 Answers

You can use .delay() with a function to do this:

d3.select(".line")
  .attr("stroke-dasharray", totalLength + " " + totalLength)
  .attr("stroke-dashoffset", totalLength)
.transition()
  .delay(function(d, i) { return i * 1000; })
  .duration(1000)
  .ease("linear")
  .attr("stroke-dashoffset", 0)
  .each("end", function() {
    d3.select(".label")
      .transition()
        .style("opacity", 1);
    });
like image 200
Lars Kotthoff Avatar answered Oct 05 '22 08:10

Lars Kotthoff