How to draw line automatically by reading coordinates from file?

两盒软妹~` 提交于 2020-01-15 06:14:54

问题


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

回答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>


来源:https://stackoverflow.com/questions/55251989/how-to-draw-line-automatically-by-reading-coordinates-from-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!