Home » Javascript » Place total figure above stacked bars in chart.js

Place total figure above stacked bars in chart.js

Posted by: admin July 11, 2018 Leave a comment

Questions:

I want to place a total value at the top of the stacked bar chart in Chart.js.

I have found this code that places the values for both parts of the stacked chart, but I only want a single value at the top of each bar https://jsfiddle.net/1ez0Lo8a/5/

animation: {
      duration: 1,
      onComplete: function () {
        var chartInstance = this.chart,
            ctx = chartInstance.ctx;
        ctx.textAlign = 'center';
        ctx.fillStyle = "rgba(0, 0, 0, 1)";
        ctx.textBaseline = 'bottom';

        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 - 5);

          });
        });
      }
    }

Even though this works somewhat, it’s not ideal for what I would like as it re-animates each time you hover – I really would prefer the label at the top to stick there.

As an aside, the animation of the bars upon load has been removed with this code – increasing duration does not seem to effect. (if you remove this animation block, the resulting animation is what I want to keep)

Answers: