将自定义标签添加到堆积条形图的顶部或底部

Str*_*ove 3 javascript chart.js

在chartjs github页面上的人们的帮助下,我得到了一个分组堆积条形图。实施很棒,并帮助我构建了我正在寻找的图表类型。我现在要添加的是一个标签来表示每个堆栈是什么。

这是我正在进行的 JS 小提琴:http : //jsfiddle.net/4rjge8sk/1/

我当前的数据集看起来像这样,我想制定一个聪明的解决方案,我可以像这样将堆栈标签添加到数据集中:

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

这是我尝试使用堆栈标签构建的预期结果: 带标签的分组堆叠条

我还不太擅长为 ChartJS 编写插件,但我想了解如何用它多画一点。谢谢你的帮助。

pot*_*ngs 5

也只需覆盖绘图功能(如果您想将其分开,您也可以将其移动到插件中 - 请参阅/sf/answers/2617570371/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();
    }
},
...
Run Code Online (Sandbox Code Playgroud)

然后只需使用您的堆栈标签代替您的堆栈索引,就像这样

...
stack: 'Stack 1'
...
Run Code Online (Sandbox Code Playgroud)

更新小提琴 - http://jsfiddle.net/bm88sd5c/

如果您希望堆栈标签具有动画效果,只需在覆盖中更改_model为。_viewdraw

完整的解决方案还会考虑堆栈标签的长度并旋转它(就像轴标签一样),但我认为这会更复杂一些。