How to handle layers with missing data points in d3.layout.stack()

后端 未结 3 1912
悲&欢浪女
悲&欢浪女 2021-02-04 00:47

I\'m using d3.stack to create a stacked area chart but I get an error if I have don\'t have an equal number of items in each layer. I\'m starting with an array of data like this

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-04 01:14

    As others have explained, it would be unreasonable for the stacked chart to guess at the missing values for each data point, because there are so many ways to interpolate the values and there is no obvious choice.

    However, d3.svg.line() seems to offer a reasonable way for you to pick your own method of interpolation and fill in missing values. While it's designed for generating SVG paths, you can probably adapt it for defining lines in general. Interpolation methods are suggested here:

    https://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-line_interpolate

    It's unfortunate that the class, for now, has all these wonderful interpolation methods (that don't appear anywhere else in d3) but is restricted to generating SVG path data instead of arbitrary intermediate values. Perhaps if @mbostock sees this, he will consider generalizing the functionality.

    However, for now you may just want to make a fork of d3 and take the intermediate result of line(data) before it is written to a SVG path string, in the part of the source that does the interpolation, below:

      function line(data) {
        var segments = [],
            points = [],
            i = -1,
            n = data.length,
            d,
            fx = d3_functor(x),
            fy = d3_functor(y);
    
        function segment() {
          segments.push("M", interpolate(projection(points), tension));
        }
    
        while (++i < n) {
          if (defined.call(this, d = data[i], i)) {
            points.push([+fx.call(this, d, i), +fy.call(this, d, i)]);
          } else if (points.length) {
            segment();
            points = [];
          }
        }
    
        if (points.length) segment();
    
        return segments.length ? segments.join("") : null;
      }
    

提交回复
热议问题