curran / d3-area-label

A library for placing labels in areas.
BSD 3-Clause "New" or "Revised" License
75 stars 4 forks source link

Use Interpolation #15

Closed curran closed 6 years ago

curran commented 6 years ago

Currently we get rather pathetic placements for small N: image

This is because the algorithm only considers X coordinates for the label from the set of X coordinates used in the data.

We could remedy this by interpolating more Y values using linear interpolation, and testing more X values than there are data values.

Here's a roughly similar bit of code that interpolates values that we could potentially draw from:

      var bisectDate = d3.bisector(function (d) {
        return d.date;
      }).left;
      function getInterpolatedValue (values, date, value){
        const i = bisectDate(values, date, 0, values.length - 1);
        if (i > 0) {
          const a = values[i - 1];
          const b = values[i];
          const t = (date - a.date) / (b.date - a.date);
          return value(a) * (1 - t) + value(b) * t;
        }
        return value(values[i]);
      }