gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot read property 'length' of undefined in d3. js

转载 作者:行者123 更新时间:2023-11-30 05:44:11 27 4
gpt4 key购买 nike

*我是 d3.js 的新手,正在尝试使用 json 文件绘制折线图,​​但出现错误,请有人帮助我。我哪里出错了。

实际上,我尝试了不同的文件格式,如 .csv 和 .tsv,但仍然出现相同的错误...

错误:未捕获类型错误:无法读取未定义的属性“长度”。

代码:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {font: 10px sans-serif;}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {display: none;}
.line {fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
</style>
<body>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://d3js.org/d3.v2.js"></script>
<script>
var arrData = [
{
"Engine": "L0",
"date": "01-Aug-13",
"value": 37.92625
},
{
"Engine": "L0",
"date": "02-Aug-13",
"value": 39.19708333
},
{
"Engine": "L1",
"date": "01-Aug-13",
"value": 44.13875
},
{
"Engine": "L1",
"date": "02-Aug-13",
"value": 43.15
},
{
"Engine": "L2",
"date": "01-Aug-13",
"value": 34.765
}];

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

var parseDate = d3.time.format.utc("%d-%b-%y").parse;

var x = d3.time.scale()
.range([0, width])

var y = d3.scale.linear()
.range([height, 0]);

var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");

var yAxis = d3.svg.axis()
.scale(y)
.orient("left");

var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.value); });

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 + ")");

var data = arrData.map(function(d) {
return {
Engine:d[0],
date: parseDate(d[1]),
value: d[2]
};

});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.value; }));

svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);

svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price ($)");

svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);

</script>
</body>

最佳答案

更改这段脚本...

var data = arrData.map(function(d) {
return {
Engine:d[0],
date: parseDate(d[1]),
value: d[2]
};
});

var data = arrData.map(function(d) {
return {
Engine: d["Engine"],
date: parseDate(d["date"]),
value: d["value"]
};
});

当它们实际上是属性时,您试图通过索引获取值,因此它们之前返回 undefined

实际上是 parseDate() 返回了错误消息。传递正确的值可以修复它。

Here's a fixed and working example...

关于javascript - 未捕获的类型错误 : Cannot read property 'length' of undefined in d3. js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18917451/

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