Question

let's say I have this d3 polygon:

var dataset = [100, 70, 50, 90, 110, 20]

//data for my line
var lineData = [];

for (var value in dataset){
lineData.push(  [{ "x": 0,   "y":200 },  { "x": 60,  "y": 200},
                { "x": 30,  "y": dataset[value]}]
                );
}



//This is the accessor function we talked about above
var lineFunction = d3.svg.line()
                         .x(function(d) { return d.x; })
                         .y(function(d) { return d.y; })
                         .interpolate("linear");

//The SVG Container
var svgContainer = d3.select("body").append("svg")
                                    .attr("width", 200)
                                    .attr("height", 200);

//The line SVG Path we draw
var lineGraph = svgContainer.append("path")
                            .attr("d", lineFunction(lineData[value]))
                            .attr("fill", "teal")
                            .attr("opacity", "0.2");

(partially courtesy of https://www.dashingd3js.com/svg-paths-and-d3js)

I'd love the vertex of my triangle to keep on changing its y position (stored in my Yvertex var for example) looping throug the values in my dataset.

Right now I'm passing as a data to write the triangle the linedata[value] var, so in the end I end up with a triangle having the vertex on the position of the last value in the dataset. I assume — but I'm probably wrong — that the dom instantly cycles between al my values and stops at the last. So is there a Way to tell D3 to take is time starting from the first value and going slow to the last value in the dataset, then from the last value go back to the first and loop the transition?

I hope to have been as clear as possible, I look forward for your help!

Was it helpful?

Solution

There are definitely easier ways to create this behavior, especially for a triangle.

But if you want a generic way to transition cycle through the path data given the way you've set up this example, you need something like the following that will cycle through each element in your lineData array and update the path accordingly:

var idx = 0;
svgContainer.on('click', function() {
    lineGraph
        .transition()
        .attr('d', lineFunction(lineData[idx]))
    idx++;
    if(idx >= dataset.length) idx = 0;
});

This one is set up to cycle through your data every time you click on the svgContainer. See here for working example: http://tributary.io/inlet/9044406

EDIT: This is an alternative version that cycles every 500ms on load: http://tributary.io/inlet/9061336

var idx = 0;
var cycle = function(){
    lineGraph
        .transition()
        .attr('d', lineFunction(lineData[idx]))
    idx++;
    if(idx >= dataset.length) idx = 0;
}

setInterval(cycle, 500)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top