如何将计算值附加到 Chart.JS 中的条形末尾?

How can I append a calculated value to the end of a bar in Chart.JS?

我正在生成如下所示的水平条形图:

我需要它看起来像这样:

也就是说,我需要将第 1 周(top/green 柱)和第 2 周(bottom/orange 柱)之间的百分比差异附加到第 2 周柱。

我正在使用以下代码将 vals 添加到条形图本身:

Chart.pluginService.register({
    afterDraw: function (chartInstance) {
        var ctx = chartInstance.chart.ctx;
        // render the value of the chart above the bar
        ctx.font = Chart.helpers.fontString(14, 'bold', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';

        chartInstance.data.datasets.forEach(function (dataset) {
            for (var i = 0; i < dataset.data.length; i++) {
                var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
                ctx.fillText(addCommas(dataset.data[i]), model.base + 20, model.y + 6);
            }
        });
    }
});

...但不知道如何进行计算并将其附加到条形的末尾。

完整 "monty" 以下是此图表的其余 jQuery:

var ctxForecastChart = $("#forecastLineChart").get(0).getContext("2d");
var forecastChartData = {
    labels: [
        "Total Qty", "Total Sales"
    ],
    datasets: [
        {
            label: "9/18/2016",
            backgroundColor: "rgba(34,139,34,0.75)",
            hoverBackgroundColor: "rgba(34,139,34,1)",
            data: [100, 1000.00]
        },
        {
            label: "9/25/2016",
            backgroundColor: "rgba(255,153,51,0.75)",
            hoverBackgroundColor: "rgba(255,153,51,1)",
            data: [110, 1110.11]
        }
    ]
};

var optionsForecast = {
    tooltips: {
        enabled: true
    }
};

var forecastBarChart = new Chart(ctxForecastChart,
{
    type: 'horizontalBar',
    data: forecastChartData,
    options: optionsForecast
});

更新

Tektiv 的代码看起来很有前途,但出于某种原因,它完全打破了我的图表。使用我的代码:

Chart.pluginService.register({
    afterDraw: function (chartInstance) {
        var ctx = chartInstance.chart.ctx;
        // render the value of the chart above the bar
        ctx.font = Chart.helpers.fontString(14, 'bold', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';

        chartInstance.data.datasets.forEach(function (dataset) {
            for (var i = 0; i < dataset.data.length; i++) {
                var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
                ctx.fillText(addCommas(dataset.data[i]), model.base + 20, model.y + 6);
            }
        });
    }
});

...我看到了这个:

用新代码替换上面的代码:

Chart.pluginService.register({
    afterDraw: function (chartInstance) {
        var ctx = chartInstance.chart.ctx;
        ctx.font = Chart.helpers.fontString(14, 'bold', Chart.defaults.global.defaultFontFamily);

        // `start` makes a better rendering IMO
        ctx.textAlign = 'start';
        ctx.textBaseline = 'bottom';
        ctx.fillStyle = '#666';

        chartInstance.data.datasets.forEach(function (dataset) {
            for (var i = 0; i < dataset.data.length; i++) {
                var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
                ctx.fillText(dataset.data[i], model.base + 5, model.y + 6);

                if (i == 1) {
                    // `Total Sales` values here

                    // If needed, here you get the other dataset
                    var otherDataset = chartInstance.data.datasets[(dataset._meta[0].controller.index == 1) ? 0 : 1];

                    // Get the value you want to display
                    var value = Math.round((Math.abs(dataset.data[i] - otherDataset.data[i]) / dataset.data[i]) * 100);

                    // Display it with the `x` property of the model
                    ctx.fillText(value + "%", model.x + 5, model.y + 6);
                }
            }
        });
    }
});

...我看到了这个:

我不知道为什么 - 新代码看起来不错,AFAICT。

更新 2

更新后的代码稍微好一点,但它仍然扭曲了其他图表:

更新 3

显然是OnDraw()事件决斗的问题;我也有这个针对价格合规图表:

Chart.pluginService.register({
    afterDraw: function (chartInstance) {
        var ctx = chartInstance.chart.ctx;
        // render the value of the chart above the bar
        ctx.font = Chart.helpers.fontString(14, 'bold', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';

        chartInstance.data.datasets.forEach(function (dataset) {
            for (var i = 0; i < dataset.data.length; i++) {
                var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
                ctx.fillText(addCommas(dataset.data[i]), model.base + 20, model.y + 6);
                //ctx.fillText(dataset.data[i], model.base + 20, model.y + 6);
            }
        });
    }
});

正如您在添加数据时对 model.base 所做的那样,请执行以下操作:

Chart.pluginService.register({
    afterDraw: function(chartInstance) {
        var ctx = chartInstance.chart.ctx;
        ctx.font = Chart.helpers.fontString(14, 'bold', Chart.defaults.global.defaultFontFamily);

        // `start` makes a better rendering IMO
        ctx.textAlign = 'start';
        ctx.textBaseline = 'bottom';
        ctx.fillStyle = '#666';

        chartInstance.data.datasets.forEach(function(dataset) {
            for (var i = 0; i < dataset.data.length; i++) {
                var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
                ctx.fillText(dataset.data[i], model.base + 5, model.y + 6);

                if (dataset._meta[0].controller.index == 1) {
                    // Orange bar (2nd dataset) values here

                    // We get the other dataset
                    var otherDataset = chartInstance.data.datasets[(dataset._meta[0].controller.index == 1) ? 0 : 1];

                    // Then calculate the percentage difference
                    var value = Math.round((Math.abs(dataset.data[i] - otherDataset.data[i]) / otherDataset.data[i]) * 100);

                    // And finally we display it
                    ctx.fillText(value + "%", model.x + 5, model.y + 6);
                }
            }
        });
    }
});


您可以看到插件正在工作 in this jsFiddle,这是它的样子: