我在创建包含数据数组的简单折线图时遇到问题。
我收到错误:错误:属性d:预期的数字," MNaN,NaNLNaN,NaNL ......"
我通过c#引入了这些数据并转换为一个看起来像这样的数组:
[
{date: "2017-08-15 16:00:00", high: "73.41", low: "73.2"},
{date: "2017-08-15 15:45:00", high: "73.38", low: "73.2715"},
{date: "2017-08-15 15:30:00", high: "73.33", low: "73.28"},
{date: "2017-08-15 15:15:00", high: "73.305", low: "73.185"},
{date: "2017-08-15 15:00:00", high: "73.22", low: "73.15"},
{date: "2017-08-15 14:45:00", high: "73.24", low: "73.1816"},
]
我试图在x轴上绘制日期,在y轴上绘制高点。我已经找到了很多这方面的问题,我在下面引用了几个。
Draw D3 Simple Line chart With an Array
Creating a line graph from array of data objects
使用我的type()函数,我可以转换' date'对象键入DateTime,然后我转换为' high'一个数字。然后我使用渲染来显示图形。
@foreach (var i in Model.Data)
{
<div>@i.Value.high</div>
}
<script>
var arrayData = [];
var i in Model.Data)
{
@:arrayData.push({date : '@i.Key', high : '@i.Value.high', low : '@i.Value.low'});
}
var outerWidth = 500;
var outerHeight = 500;
var margin = { left: 30, top: 30, right: 30, bottom: 30 };
var xColumn = "date";
var yColumn = "high";
// parse the date / time
var parseTime = d3.timeParse("%d-%b-%y");
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", outerWidth)
.attr("height", outerHeight);
//create a group
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//append a path element to our group
var path = g.append("path");
var innerWidth = outerWidth - margin.left - margin.right;
var innerHeight = outerHeight - margin.top - margin.bottom;
//set ranges
var xScale = d3.scaleTime().range([0, innerWidth]);
var yScale = d3.scaleLinear().range([innerHeight, 0]);
//changed the below from d[xColumn] to d.date
var line = d3.line()
.x(function (d) { return xScale(d.xColumn); })
.y(function (d) { return yScale(d.yColumn); });
//changed the below from d[xColumn] to d.date
function render(data) {
xScale.domain(d3.extent(data, function (d) { return d.date; }));
yScale.domain(d3.extent(data, function (d) { return d.high; }));
path.attr("d", line(data));
}
function type(d) {
d.date = new Date(d.date);
d.date = parseTime(d.date);
d.high = +d.high;
d.low = + d.low;
return d;
}
//below i have deterrmined that the type conversion is working by calling type() on the arrayData; i checked the arrayData.date before then after and saw it was converted to a object; I then checked
//to see if this was an instance of a date
console.log(arrayData.date);
type(arrayData);
var temp3 = (arrayData.date instanceof Date);
console.log(temp3);
var temp = typeof arrayData.date;
var temp2 = typeof arrayData.high;
console.log(temp);
console.log(temp2);
//try and run graph now
render(arrayData);
</script>
经过全面搜索,对我来说,看起来我的格式正确。我是d3的新手,无法弄清楚我做错了什么。有人可以帮忙吗?
答案 0 :(得分:1)
引用对象属性的方式在javascript中不起作用。
您指定:
var xColumn = "date";
var yColumn = "high";
然后尝试引用d.date
和d.high
:
.x(function (d) { return xScale(d.xColumn); })
.y(function (d) { return yScale(d.yColumn); });
d.yColumn
和d.xColumn
将返回undefined
。如果您想以这种方式引用它们,则需要使用以下符号:d[xColumn]
和d[yColumn]
。