3

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?

Community
  • 1
  • 1
ekatz
  • 1,050
  • 1
  • 11
  • 29

1 Answers1

2

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.

ValarDohaeris
  • 6,064
  • 5
  • 31
  • 43
  • This is as elegant as it gets. Thanks for posting, this teaches me much more than just the question (I'm a little new to javascript)! – ekatz Jan 15 '14 at 22:12