You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决d3.js堆叠面积图报错「Expected number, "MNaN,331.050055LN…」?

问题根因

报错的核心原因是d3的时间比例尺scaleTime要求输入的domain值必须为Date类型,你的代码中初始化x轴比例尺时直接传入了字符串格式的日期,导致比例尺计算坐标时返回NaN,最终出现<path> attribute d: Expected number, "MNaN,..."错误。
你确认stackedData符合预期是因为堆叠逻辑只处理了数值字段,和x轴坐标计算逻辑无关,所以不影响错误触发。

修复步骤
  • 先统一将原始数据中的日期字符串转换为Date类型,避免重复解析
  • 修改x轴比例尺的domain取值,直接使用转换后的Date对象
  • (可选优化)y轴的domain不要写死为0-5000,根据堆叠数据的最大值动态计算,避免图表显示过于压缩
修复后代码
// set the dimensions and margins of the graph
var margin = {top: 20, right: 30, bottom: 30, left: 55},
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

// 统一转换日期格式
const parseTime = d3.timeParse('%Y-%m-%d');
temp.forEach(d => d.date = parseTime(d.date));

// append the svg object to the body of the page
var svg = d3.select("#my-stacked-chart")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

//  X axis 直接使用转换后的Date对象生成domain
const x = d3
  .scaleTime()
  .domain(d3.extent(temp, d => d.date))
  .range([0, width]);
svg
  .append('g')
  .attr('transform', `translate(0, ${height})`)
  .call(d3.axisBottom(x).ticks(4));

// grouping data by date
let groupByDate = d3.nest()
  .key(d => d.date)
  .entries(temp);

// stacked groups
var stackedData = d3.stack()
  .keys(['RED', 'BLUE'])
  .value(function(d, key){
    return d.values.find(i => i.category === key).minutes
  })(groupByDate)

// 动态计算y轴domain,取堆叠后的最大值
const maxY = d3.max(stackedData[stackedData.length - 1], d => d[1]);
const y = d3
  .scaleLinear()
  .domain([0, maxY])
  .range([height, 0]);
svg.append('g').call(d3.axisLeft(y).ticks(3));

// Show the areas,x参数直接将key转回Date即可
svg
  .selectAll("mylayers")
  .data(stackedData)
  .enter()
  .append("path")
    .attr("d", d3.area()
      .x(function(d) { return x(parseTime(d.data.key)) })
      .y0(function(d) { return y(d[0]); })
      .y1(function(d) { return y(d[1]); })
  )

内容的提问来源于stack exchange,提问作者user10368959

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 19:15:01