gpt4 book ai didi

javascript - 来自 csv 的 D3 中的 svg 行(作为单独的行而不是一行)-不显示

转载 作者:行者123 更新时间:2023-12-02 14:17:35 28 4
gpt4 key购买 nike

我正在 d3.js 中绘制一些 svg 线我以这种方式设置它,而不是使用 d3.svg.line() ,这样每行都是单独的,我可以给每个行一个不同的类。但是,我的行没有显示,因为它们没有获取 y2 属性。

控制台截图: enter image description here

关于如何让它发挥作用有什么想法吗?

代码:

    <!DOCTYPE html>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>

var margin = {top: 20, right: 20, bottom: 20, left: 20},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;

var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.csv("data.csv", function(error, data){

svg.selectAll("line")
.data(data)
.enter().append("svg:line")
.attr("x1", function(d, i) { return data[i].x })
.attr("y1", function(d, i) { return data[i].y})
.attr("x2", function(d, i) { return data[i+1].x})
.attr("y2", function(d, i) { return data[i+1].y})
.attr("fill", "none")
.attr("stroke", "red")
.attr("class", function(d,i){return "line" + i;});
});

</script>

Here is a Plunker ,其中还包括数据。

最佳答案

您的 x2 和 y2 函数将在数组中的最终对象上出错,因为它们试图访问不存在的下一行。例如你的 array.length 是 258 并且你在第 257 行; x2 和 y2 函数将尝试访问不存在的第 258 行。尝试:

svg.selectAll("line")
.data(data)
.enter().append("svg:line")
.attr("x1", function(d, i) { return data[i].x; })
.attr("y1", function(d, i) { return data[i].y; })
.attr("x2", function(d, i) {

// this the fix
// if there is a line at i+1 we will use it
// otherwise use the line at index 0
return data[i+1] ? data[i+1].x : data[ 0 ].x ;

})
.attr("y2", function(d, i) {

// same as above but for y
return data[i+1] ? data[i+1].y : data[ 0 ].y ;

})
.attr("fill", "none")
.attr("stroke", "red")
.attr("class", function(d,i){return "line" + i;});

关于javascript - 来自 csv 的 D3 中的 svg 行(作为单独的行而不是一行)-不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38906387/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com