如何通过从文件中读取坐标自动绘制线? [英] 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.x1= +d.x1;
d.y1= +d.y1;
d.x2= +d.x2;
d.y2= +d.y2;
});
所以输入就像
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;
...不正确.在d3.csv
内部完成.
... is not correct. Do it inside d3.csv
.
这是一个包含您的数据的演示(由于所有坐标都非常小且没有比例,因此我将viewBox
与SVG配合使用):
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>
这篇关于如何通过从文件中读取坐标自动绘制线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!