我有这个D3js代码:

var dataset=JSON.parse('{"date": ["2016-11-28", "2016-11-29", "2016-12-01", "2016-12-02", "2016-12-03", "2016-12-04", "2016-12-05", "2016-12-06", "2016-12-07", "2016-12-08", "2016-12-09", "2016-12-10", "2016-12-11"], "bca": [{"JPY": 119, "USD": 13510, "SGD": 9455, "CNY": 1944}, {"JPY": 120, "USD": 13527, "SGD": 9491, "CNY": 1951}, {"JPY": 118, "USD": 13560, "SGD": 9459, "CNY": 1959}, {"JPY": 119, "USD": 13535, "SGD": 9498, "CNY": 1968}, {"JPY": 118, "USD": 13485, "SGD": 9470, "CNY": 1958}, {"JPY": 118, "USD": 13485, "SGD": 9470, "CNY": 1958}, {"JPY": 118, "USD": 13485, "SGD": 9470, "CNY": 1958}, {"JPY": 117, "USD": 13430, "SGD": 9435, "CNY": 1952}, {"JPY": 117, "USD": 13382, "SGD": 9426, "CNY": 1944}, {"JPY": 116, "USD": 13327, "SGD": 9379, "CNY": 1931}, {"JPY": 117, "USD": 13278, "SGD": 9375, "CNY": 1926}, {"JPY": 116, "USD": 13322, "SGD": 9360, "CNY": 1923}, {"JPY": 116, "USD": 13322, "SGD": 9360, "CNY": 1923}], "maybank": [{"JPY": 119, "USD": 13510, "SGD": 9463, "CNY": 1945}, {"JPY": 120, "USD": 13520, "SGD": 9487, "CNY": 1951}, {"JPY": 119, "USD": 13550, "SGD": 9509, "CNY": 1964}, {"JPY": 118, "USD": 13540, "SGD": 9466, "CNY": 1961}, {"JPY": 118, "USD": 13490, "SGD": 9477, "CNY": 1961}, {"JPY": 118, "USD": 13490, "SGD": 9477, "CNY": 1961}, {"JPY": 118, "USD": 13490, "SGD": 9477, "CNY": 1961}, {"JPY": 117, "USD": 13420, "SGD": 9428, "CNY": 1951}, {"JPY": 117, "USD": 13380, "SGD": 9426, "CNY": 1944}, {"JPY": 116, "USD": 13330, "SGD": 9373, "CNY": 1931}, {"JPY": 116, "USD": 13270, "SGD": 9368, "CNY": 1926}, {"JPY": 116, "USD": 13320, "SGD": 9358, "CNY": 1923}, {"JPY": 116, "USD": 13320, "SGD": 9358, "CNY": 1923}]}');
var svg = d3.select(".tes").append("svg").attr("width", 800).attr("height", 450);
var parsetime = d3.timeParse("%y-%m-%d");
var ya=[];
for (var i=0;i<dataset['date'].length;i++){
     ya.push({"x":parsetime(dataset['date'][i]),"y":dataset['maybank'][i]['JPY']});
}
var xS = d3.scaleTime().range([0,750]);
var yS = d3.scaleLinear().range([400,0]);
var valueline = d3.line().x(function(d){return xS(d.x);}).y(function(d){return yS(d.y);});
xS.domain([d3.extent(ya, function(d) { return d.x; })]);
yS.domain([0, d3.max(ya, function(d) { return d.y; })]);
svg.append("path").data([ya]).attr("class","line").attr("d", valueline);
svg.append('g').attr("transform", "translate(35,"+ 400 +")").call(d3.axisBottom(xS));
svg.append("g").attr("transform", "translate(" + 35 + ",0)").call(d3.axisLeft(yS));


我发现parseTime总是返回null。因此无法创建折线图。 parseTime是否必须在d3数据函数内部,例如d3.tsv,d3.json等?但是从我的json数据中很难做到。还是有其他建议可以使此工作有效?

最佳答案

您的格式说明符%y-%m-%d不正确。

根据D3 documentation%y是2位数字年份的指令,而%Y是4位数字年份的指令。您使用的是4位数字的年份,因此需要%Y而不是%y

关于javascript - D3v4 timeParse始终返回null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41086438/

10-13 05:56