如何按年累计 d3.rollup 数据

How to cumulate d3.rollup data by year

我想创建一个每年累积的折线图。
我的数据是天数和值的无序列表:

date        value
2019-10-10  32.3104
2020-12-29  190.4676
2019-01-02  400.1440
2020-12-21  100.0
2020-12-21  347.1200
2019-01-02  30.6
...

我想每年创建一条线,所以我对数据进行排序并使用 rollup 对数据进行求和和分组:

data = {
  const sortedData = rawdata.sort((a, b) => d3.ascending(a.date, b.date));
  return d3.rollup(
    sortedData,
    (v) => d3.sum(v, (d) => d.value),
    (d) => d.date.getFullYear(),
    (d) => d.date
  );  
}

通过这种方式,我使用 d3.join

得到了每年的图表
svg.append("g")
  .selectAll('.line')
  .data(data.values())
  .join(
    (enter) =>
      enter
        .append('path')
        .attr('class', 'line')
        .attr('fill', 'none')
        .attr('stroke', (d, i) => colors[i])
        .attr('stroke-width', 1.5)
        .attr('d', line),
    (update) =>
      update.attr('d', line),
  );

现在我希望这条线每年累加,但我不知道如何使用 d3.cumsum 来累加每年的总和。

我不知道如何对这些汇总数据求和 - 有人可以帮我吗?

Here is a full working example of my chart on ObservableHQ

如果您希望数据保持与当前相同的格式,这样您就不必更改任何其他代码,那么您可以这样做

data = {
  const sortedData = rawdata.sort((a, b) => d3.ascending(a.date, b.date));

  // rollups returns arrays of key-value pairs instead of a map
  const groupByYearDate = d3.rollups(
      sortedData,
      (v) => d3.sum(v, (d) => d.value),
      (d) => d.date.getFullYear(),
      (d) => d.date
    );
  
  return new Map(
    // for each year
    groupByYearDate.map(([year, values]) => {
      // summed is an array of numbers
      const summed = d3.cumsum(values, d => d[1]);
      // dates is an array of dates
      const dates = values.map(d => d[0]);
      // zip them together
      const combined = d3.zip(dates, summed);
      return [year, new Map(combined)]
    })
  );
}

这里有一个略有不同的 example,它对您的代码进行了额外的更改。