score:1

Accepted answer

you need to change the formatter function to make it work.

the total value shall appear on the top most value of the stacked bars only. the stacked bars however don't contain zero values nor values from hidden datasets. i ended up with the following solution that works but can probably be improved/simplified.

const formatter = (value, ctx) => {
  const stackedvalues = ctx.chart.data.datasets
    .map((ds) => ds.data[ctx.dataindex]);
  const dsidxlastvisiblenonzerovalue = stackedvalues
    .reduce((prev, curr, i) => !!curr && !ctx.chart.getdatasetmeta(i).hidden ? math.max(prev, i) : prev, 0);
  if (!!value && ctx.datasetindex === dsidxlastvisiblenonzerovalue) {
    return stackedvalues
      .filter((ds, i) => !ctx.chart.getdatasetmeta(i).hidden)
      .reduce((sum, v) => sum + v, 0);
  } else {
    return "";
  }
};

please take a look at your amended code sandbox and see how it works.


Related Query