In d3Js, How would one draw basic line segments from a tsv file? Say the file declare, in one row of data, x1,y1,x2,y2. I want to draw two line segments as in the data below:<
The code below should work. Depending on your style, you may want to organize files and code differently, but the key part you must include is chain selectAll("line").data(data).enter().append("line"). This is the most frequent D3 idiom, and also the one that gives the hardest time to everyone learning D3 - especially to those that come from the background of procedural languages. You can look up D3 documentation, but I will also try to write down something on this topic later today.
data/sampledata.tsv:
same as yours.
index.html:
Two Lines
Two Lines
script.js:
function load(){
var svg = d3.select("body")
.append("svg")
.attr("width", 1000)
.attr("height", 1000);
d3.tsv("data/sampledata.tsv", function(error, data) {
svg.selectAll("line")
.data(data)
.enter()
.append("line")
.attr("x1", function(d) { return (1000 * d.x0); })
.attr("y1", function(d) { return (1000 * d.y0); })
.attr("x2", function(d) { return (1000 * d.x1); })
.attr("y2", function(d) { return (1000 * d.y1); })
.attr("stroke-width", function(d) { return (d.weight); })
.attr("stroke", "black");
});
};
The code in action is here. IT produces following page: