Can't seem to properly fetch the data from JSON. My chart is not even able to be displayed. Any ideas on how i can fix this?
<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>
Notes:
- The ask and bid of bboList, and the price of tradeList are in hundreds of pennies so 233200 --> $23.32
The time in tradeList is in nanoseconds so 34574353918784 --> 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"}, ...
d3.json
does not accept an accessor (or row) function. It has to be just:
d3.json(url[, callback])
In your code:
d3.json("bboList.json", function(d) {
d.timeStr = parseTime(d.timeStr);
d.bid = +d.bid;
return d;
}, function(error, data) {
if (error) throw error;
//...
});
Everything between the URL and function(error, data)
is the row function.
Solution: remove it, and coerce the values to numbers and dates using a forEach
:
d3.json("bboList.json", function(error, data) {
if (error) throw error;
data.forEach(d => {
d.timeStr = parseTime(d.timeStr);
d.bid = +d.bid;
});
/...
});
来源:https://stackoverflow.com/questions/42475033/d3-json-stock-chart-not-displaying