首页 > 解决方案 > 在 D3.js 中查找两个日期之间的中间日期

问题描述

我正在使用 D3.js 散点图根据时间段显示作品数量。我想在每个时期的开始日期和结束日期之间的中间日期放置点。我拥有的数据如下所示:

period, amount, startDate, endDate
1, 5, 26/11/1982, 2/6/1989
2, 6, 2/6/1989,2/1/1990
3, 11, 2/01/1990,20/6/1999

我尝试使用以下方法在图表上映射点:

.attr("cx", function(d) { return xScale(new Date(d.endDate)) - xScale(new Date(d.startDate)) * 0.5 })

但这不起作用。我错过了什么?

标签: javascriptd3.js

解决方案


两个给定点之间的中点是:

middleX = (x1 + x2) / 2;

在你的情况下:

d => {
  const xFrom = xScale(new Date(d.startDate));
  const xTo = xScale(new Date(d.endDate));
  return (xFrom + xTo) / 2;
}

推荐阅读