似乎无法从JSON正确获取数据。我的图表甚至无法显示。关于如何解决这个问题的任何想法?
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 30, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var parseTime = d3.timeParse("%d-%b-%y");
var x = d3.scaleTime()
.rangeRound([0, width]);
var y = d3.scaleLinear()
.rangeRound([height, 0]);
var line = d3.line()
.x(function(d) { return x(d.timeStr); })
.y(function(d) { return y(d.bid); });
d3.json("bboList.json", function(d) {
d.timeStr = parseTime(d.timeStr);
d.bid = +d.bid;
return d;
}, function(error, data) {
if (error) throw error;
x.domain(d3.extent(data, function(d) { return d.timeStr; }));
y.domain(d3.extent(data, function(d) { return d.bid; }));
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
.select(".domain")
.remove();
g.append("g")
.call(d3.axisLeft(y))
.append("text")
.attr("fill", "#000")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text("Price ($)");
g.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("stroke-width", 1.5)
.attr("d", line);
});
</script>
注意:
tradeList中的时间以纳秒为单位,因此34574353918784 - &gt; 09:36:14.353
{"bboList":[{"ask":235400,"bid":231800,"timeStr":"09:30:00.000"},
{"ask":235400,"bid":230900,"timeStr":"09:30:07.819"},
{"ask":238300,"bid":230900,"timeStr":"09:30:07.819"},
{"ask":238300,"bid":227500,"timeStr":"09:30:26.786"},
...
答案 0 :(得分:1)
d3.json
不接受访问者(或行)功能。它必须只是:
d3.json(url [,callback])
在您的代码中:
d3.json("bboList.json", function(d) {
d.timeStr = parseTime(d.timeStr);
d.bid = +d.bid;
return d;
}, function(error, data) {
if (error) throw error;
//...
});
网址和function(error, data)
之间的所有内容都是行功能。
解决方案:将其删除,并使用forEach
将值强制转换为数字和日期:
d3.json("bboList.json", function(error, data) {
if (error) throw error;
data.forEach(d => {
d.timeStr = parseTime(d.timeStr);
d.bid = +d.bid;
});
/...
});