简体   繁体   中英

Add a custom label to the top or bottom of a stacked bar chart

I've got a grouped stacked bar chart with some help from the folks on the chartjs github page. The implementation is great and has helped me build the type of chart I'm looking for. What I'm trying to add now is a label to denote what each of the stacks are.

Here is the JS fiddle I have in progress: http://jsfiddle.net/4rjge8sk/1/

my current dataset looks like this and I would like to make a clever solution where I could add a stack label into the dataset like so:

datasets: [
    {
      label: "Apples",
      backgroundColor: "rgba(99,255,132,0.2)",
      data: [20, 10, 30],
      stack: 1,
      stackLabel: "Stack 1"
    }

And here is the desired outcome I'm trying to build with the stack labels: 带有标签的分组堆积栏

I'm not great with writing a plugin for ChartJS just yet but I would like to understand how to draw with it a little more. Thanks for any help.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM