Skip to content Skip to sidebar Skip to footer

How To Draw Line Automatically By Reading Coordinates From File?

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

Solution 1:

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>

Post a Comment for "How To Draw Line Automatically By Reading Coordinates From File?"