0
我無法用數據數組創建簡單折線圖。d3.js用DateTime和int數組創建簡單的折線圖
我收到錯誤:錯誤:屬性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
用我喜歡的類型()函數I轉換 '約會' 對象鍵入日期時間和我轉換 '高' 了許多。然後我使用渲染來顯示圖形。
@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新手,無法弄清楚我做錯了什麼。有人可以幫忙嗎?
這個伎倆!非常感謝先生,我會接受這個答案。關於我引用我的對象的方式,我認爲通過點符號引用被允許在JavaScript中,如下所述:https://www.w3schools.com/js/js_properties.asp – Joe
很高興它的工作!點符號不起作用,你只能在點後面使用變量。 –
我在x軸上插入'數字'以使其工作。但是一旦我開始在x軸上再次使用日期,我會收到錯誤:'屬性d:預期編號,「MNaN,72.084347120 ...」'你知道這是爲什麼嗎?它似乎仍然期待在x軸上有一個數字 –
Joe