在获取折线图上的JSON数据时遇到问题,我可以完全以条形图的方式进行此操作,但是由于某种原因,在制作折线图时会出现错误。周围没有太多文档,所以看看是否有人知道。
我得到这个错误
错误:解析d =“ MNaN,400LNaN,258.65447419986936LNaN,221.90289571086436LNaN,183.32244720226433LNaN,134.29131286740693LNaN,149.70607446113652LNaN,63.1395602003048LNaN,37.448290910422L69NNaN,69。
JSON数据如下:
[{“ logins”:“ 3333”,“ month_name”:“一月”},{“ logins”:“ 4956”,“ month_name”:“二月”},{“ logins”:“ 5378”,“ month_name”: “ March”},{“ logins”:“ 5821”,“ month_name”:“ April”},{“ logins”:“ 6384”,“ month_name”:“ May”},{“ logins”:“ 6207”, “ month_name”:“六月”},{“ logins”:“ 7201”,“ month_name”:“ July”},{“ logins”:“ 7496”,“ month_name”:“ August”},{“ logins”: “ 7129”,“ month_name”:“ 9月”},{“ logins”:“ 7926”,“ month_name”:“ 10月”},{“ logins”:“ 5975”,“ month_name”:“ 11月”},{ “ logins”:“ 540”,“ month_name”:“ December”}]
现在的代码:
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = $("svg").parent().width();
height = $("svg").parent().height();
aspect = 500 / 950;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.x(function(d) { return x(d.month_name); })
.y(function(d) { return y(d.logins); });
var svg = d3.select(document.createElement("div")).append("svg")
.attr("preserveAspectRatio", "xMidYMid")
.attr("viewBox", "0 0 950 500")
.attr("width", width)
.attr("height", width * aspect)
.attr("id", "art_chart")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(d3.extent(data, function(d) { return d.month_name; }));
y.domain(d3.extent(data, function(d) { return d.logins; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Logins");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
有人知道如何解决它,以便显示折线图吗?
最佳答案
您需要解析日期并将数字作为数字传递:
data.forEach(function(d) {
d.month_name = d3.time.format("%B").parse(d.month_name);
d.logins = +d.logins;
});
如果您是在加载JSON之后立即运行此代码的,那么一切都会正常运行。