I am trying to draw line with arrow at one end. Also I need to do it automatically for multiple arrows in the same plot.
d3.csv("/data/coordinates.csv").then(function(data) {
d.x1= +d.x1;
d.y1= +d.y1;
d.x2= +d.x2;
d.y2= +d.y2;
});
so input will be like
x1,y1,x2,y2
1,2,3,2
3,3,5,4
5,3,6,3
7,5,7,5
8,6,8,6
9,7,2,8
var xoneValue = function(d) { return d.x1;},
xoneMap = function(d) { return xoneValue(d);};
var yoneValue = function(d) { return d.y1;},
yoneMap = function(d) { return yoneValue(d);};
var xtwoValue = function(d) { return d.x2;},
xtwoMap = function(d) { return xtwoValue(d);};
var ytwoValue = function(d) { return d.y2;},
ytwoMap = function(d) { return ytwoValue(d);};
i found the following code but how can i loop through this code as the data is in file?
holder.append("line") // attach a line
.style("stroke", "black") // colour the line
.attr("x1", xoneMap ) // x position of the first end of the line
.attr("y1", xtwoMap ) // y position of the first end of the line
.attr("x2", xtwoMap ) // x position of the second end of the line
.attr("y2", ytwoMap ); // y position of the second end of the line
All you need is an enter selection. For instance:
const enterSelection = svg.selectAll(null)
.data(data)
.enter()
.append("line")
//etc...
By the way, all those lines...
var xoneValue = function(d) { return d.x1;},
xoneMap = function(d) { return xoneValue(d);};
... are not doing anything, they are simply retuning the value as it is. Also, your attempt of creating a row function...
d.x1= +d.x1;
d.y1= +d.y1;
d.x2= +d.x2;
d.y2= +d.y2;
... is not correct. Do it inside d3.csv
.
Here is a demo with your data (since all coordinates ave very small and you have no scale, I'm engaging the SVG with a viewBox
):
const csv = `x1,y1,x2,y2
1,2,3,2
3,3,5,4
5,3,6,3
7,5,7,5
8,6,8,6
9,7,2,8`;
const data = d3.csvParse(csv, function(d) {
d.x1 = +d.x1;
d.y1 = +d.y1;
d.x2 = +d.x2;
d.y2 = +d.y2;
return d;
});
const svg = d3.select("svg");
const enterSelection = svg.selectAll(null)
.data(data)
.enter()
.append("line")
.attr("x1", d => d.x1)
.attr("y1", d => d.y1)
.attr("x2", d => d.x2)
.attr("y2", d => d.y2)
.style("stroke-width", "1px")
.style("stroke", "black")
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg viewBox="0 0 20 20"></svg>