chartjs / chartjs-plugin-datalabels

Chart.js plugin to display labels on data elements
https://chartjs-plugin-datalabels.netlify.app
MIT License
873 stars 473 forks source link

Horizontal stacked barchart with negative values label position is off #407

Open aapjaapan opened 8 months ago

aapjaapan commented 8 months ago
Screenshot 2024-01-16 at 10 51 38

The sum of the bar is shown wrong when there are negative values it the stack and last stack value is 0 (which is so it is not shown in bar on the image)

      datalabels: {
        formatter: (value, ctx) => {
          const datasets = ctx.chart.data.datasets;
          if (datasets.indexOf(ctx.dataset) === datasets.length - 1) {
            let sum = 0;
            datasets.map((dataset) => {
              sum += dataset.data[ctx.dataIndex] as number;
            });
            return sum.toFixed(2);
          } else {
            return '';
          }
        },
        anchor: 'end',
        align: 'end',
      },