[Chartjs]-Chart js sum of grouped bars

0👍

you can try something like this fiddle, but i did not format and position the labels as of now, you can do it as you wish.

"onComplete": function() {
        var chartInstance = this.chart,
          ctx = chartInstance.ctx;
          ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
          ctx.textAlign = 'center';
          ctx.textBaseline = 'bottom';
           var sums = [0, 0, 0];
          this.data.datasets.forEach(function(dataset, i) {
            var meta = chartInstance.controller.getDatasetMeta(i);
            meta.data.forEach(function(bar, index) {
              var data = dataset.data[index];
              ctx.fillText(data, bar._model.x, bar._model.y);
              sums[index] += data;
            });
            });
          sums.forEach(function(v, i) {
            ctx.fillText(v, 150*(i+1)+(i*50), 40);
          });
        }

0👍

The formatter is called for each datalabel, meaning for every bar. That’s the reason why you get the same value on top of every bar.

Possible solutions would be either to plot an “invisible” bar for the combined value or check inside the formatter function if it is called for the centered bar. Then you could use mulitline labels to create a label which has the value for the current bar and the combined value as well.

Edit:

After thinking about it the easiest way would be to use mixed charts. You can just calculate your combined values for each group and add a chart for these values. For example you add a line chart with showLines: false.

new Chart('myMixedCharts', {
    type: 'bar',
    data: {
        labels: ['foo', 'bar'],
        datasets: [
          {
            label: "Value 1",
            data: [12, 5]
          },
          {
            label: "Value 2",
            data: [7, 8]
          },
          {
            label: "Group value",
            data: [19, 13],
            type: "line",
            showLines: false
          }
        ]
    }
});

Or as jsFiddle

Leave a comment