[Chartjs]-Add a custom label to the top or bottom of a stacked bar chart

5👍

Just override the draw function too (you can move it to a plugin too if you want to keep it separate – see https://stackoverflow.com/a/37393862/360067) in groupableBar

...
draw: function(ease) {
    Chart.controllers.bar.prototype.draw.apply(this, arguments);

    var self = this;
    // check if this is the last dataset in this stack
    if (!this.chart.data.datasets.some(function (dataset, index) { return (dataset.stack === self.getDataset().stack && index > self.index); })) {
        var ctx = this.chart.chart.ctx;
        ctx.save();
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';
        ctx.fillStyle = this.chart.options.defaultFontColor;
        // loop through all its rectangles and draw the label
        helpers.each(self.getMeta().data, function (rectangle, index) {
            ctx.fillText(this.getDataset().stack, rectangle._model.x, rectangle._model.y)
        }, this);
        ctx.restore();
    }
},
...

and then just use your stack labels in place of your stack index, like so

...
stack: 'Stack 1'
...

Updated fiddle – http://jsfiddle.net/bm88sd5c/

If you want your stack labels to animate, just change _model to _view in the draw override.

A full solution would also consider the length of the stack label and rotate it (just like axis labels), but I think that’s going to be a tad more complicated.

Leave a comment