hotshotiguana
hotshotiguana

Reputation: 1560

d3 Animate Multiple SVG Lines

I'm trying to create multiple lines on a line graph one at a time. I've created an object array of about 100 lines in the below format:

var allLines = [{type: "linear", values: [1000, 2000, 3000]}, {}, ... {}];

var line = d3.svg.line()
    .defined(function (d) {
        return d != null;
    })
    .x(function (d, i) {
        return x(new Date(minYear + i, 1, 1));
    })
    .y(function (d) {
        return y(d);
    });

Now I want to draw each line, one at a time with a delay of about 250 milliseconds between each line. I've tried the below approach which I thought would work, but I must be missing something because it just waits 250ms and then draws all the lines.

svg.append('g')
    .attr('class', 'lineGroup')
    .selectAll('path')
    .data(allLines)
    .enter()
    .append('path')
    .attr('class', function (d) {
        return d.type;
    })
    .style('visibility', 'hidden')
    .attr('d', function (d) {
        return line(d.values);
    });

    function foo(transition) {
        transition
            .style('visibility', 'visible');
    }

    d3.select('.lineGroup').selectAll('path').transition().delay(250).call(foo);

Upvotes: 0

Views: 836

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

Your basic approach is right, you just need to adjust the delay dynamically such that the later lines are drawn later. At the moment, the delay applies to all lines. To make it dynamic, you can use something like

svg.append("g")
   // etc
   .transition()
   .delay(function(d, i) { return i * 250; })
   .style('visibility', 'visible');

You can also do everything in one call, no need for a separate one after creating the lines.

Upvotes: 1

Related Questions