D3.js多折线图日期格式异常无法渲染问题求助
解决D3.js多折线图渲染NaN报错问题
看起来你遇到的核心问题是line函数生成的路径数据包含NaN,导致SVG无法正确渲染折线。报错信息attribute d: Expected number, "MNaN,293.27586206…"说明第一个点的x坐标是NaN,而y坐标是正常的,我们可以从几个方向排查和修复:
1. 确保日期被正确解析为Date对象
你的代码里用d3.timeParse("%Y-%m-%d")转换日期,但如果解析失败会返回null,而x(null)会直接返回NaN。可以在日期转换后添加日志验证:
data.forEach(function(d){ d.Date = parseTime(d.Date); console.log("Parsed date:", d.Date); // 确认输出是有效的Date对象,而非null });
如果发现解析失败,检查日期字符串格式是否和%Y-%m-%d完全匹配(你的数据格式是对的,但可以确认下是否有隐藏的空格或特殊字符)。
2. 显式转换SVG宽高为数字
svg.attr("width")和svg.attr("height")返回的是字符串,虽然JavaScript会自动转换,但显式转为数字能避免潜在的类型问题:
width = +svg.attr("width") - margin.left - margin.right, height = +svg.attr("height") - margin.top - margin.bottom,
这里的+号会把字符串强制转为数字,确保后续scale的range是有效的数值范围。
3. 验证Line函数的访问器返回值
在line函数里添加日志,确认每个点的x和y值是否正常:
var line = d3.line() .curve(d3.curveBasis) .x(function(d) { const xVal = x(d.Date); console.log("X input:", d.Date, "X output:", xVal); return xVal; }) .y(function(d) { const yVal = y(d.temperature); console.log("Y input:", d.temperature, "Y output:", yVal); return yVal; });
通过日志可以直接看到哪个值导致了NaN,比如如果d.Date是null,那xVal就是NaN。
4. 确认Y轴Domain的有效性
检查Y轴的domain是否是有效的数值范围,避免包含NaN:
const yDomain = [ d3.min(cities, function(c) { return d3.min(c.values, function(d) { return d.temperature; }); }), d3.max(cities, function(c) { return d3.max(c.values, function(d) { return d.temperature; }); }) ]; console.log("Y domain:", yDomain); // 确认两个值都是数字,而非NaN y.domain(yDomain);
如果这里出现NaN,说明你的cities数据里存在temperature为undefined或非数字的情况,需要检查数据映射逻辑。
额外的代码优化
- 你的
make_x_axis函数可以简化,直接把scale传给axisBottom:
function make_x_axis() { return d3.axisBottom(x).ticks(12); }
- 给Y轴的调用语句补上分号,避免潜在的语法问题:
g.append("g") .attr("class", "axis axis--y") .call(d3.axisLeft(y)); // 补上分号
按照这些步骤排查,应该能找到并修复导致NaN的问题,让折线图正常渲染。
内容的提问来源于stack exchange,提问作者Chetan
相关产品推荐
相关产品推荐

