Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3JS: iterate through paths of unknown point count

This question is an extension of an original question regarding line segments.

In regards to the original question, the issue of drawing line segments from a tsv has been solved with this script (thanks to @VividD). Here is the data for drawing two line segments from a tsv:

x0      y0      x1      y1      weight
0.5     0.5     0.2     0.2     2
0.25    0.35    0.7     0.8     1

Now, I am trying to draw paths (or polylines) with an unknown number of vertices. This would require the script to iterate through each row, looking for the number of columns to add to the data for each path. I'm unaware of how to do this because the scripts I've been working with assumption that the programmer knows the column names (d.close, d.date, etc.).

x0      y0      x1      y1      x2      y2           weight
0.5     0.5     0.2     0.2                          2
0.25    0.35    0.7     0.8     0.5     0.6          1

Does anyone have an idea for how to iterate through the example above, drawing paths for each row of data?

like image 413
ekatz Avatar asked Dec 04 '25 08:12

ekatz


1 Answers

Assuming the data is in array data, this will create an array points of variable length for each of your tuples:

data.forEach(function(d) {
    d.points = [];
    for (var i = 0; d["x"+i] !== "" && (typeof d["x"+i] !== 'undefined'); i++) {
        d.points.push([d["x"+i], d["y"+i]]);
    }
});

E.g. for the first row in your example

d.points = [[0.5, 0.5], [0.2, 0.2]]

Which can then be used to draw the lines:

var line = d3.svg.line();

svg.selectAll("path")
    .data(data)
    .enter()
    .append("path");

svg.selectAll("path")
    .attr("d", function(d) { return line(d.points); })
    .attr("stroke-width", function(d) { return (d.weight); })
    .attr("stroke", "black")
    .attr("fill", "none");

Full example here.

like image 131
ValarDohaeris Avatar answered Dec 05 '25 21:12

ValarDohaeris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!