如何在Chart.JS条形图中的最后一个条形图上方添加标签?

时间:2016-09-27 22:00:18

标签: javascript drawing draw chart.js chart.js2

我正在创建一个如此的条形图:

var ctxForecastChart = $("#forecastLineChart").get(0).getContext("2d");
var forecastChartData = {
    labels: [
        "Total Sales"
    ],
    datasets: [
    {
        label: "8/28/2016 - 9/3/2016",
        backgroundColor: "rgba(255,0,0,0.75)",
        hoverBackgroundColor: "rgba(255,0,0,1)",
        data: [240]
    },
    {
        label: "9/25/2016 - 10/2/2016",
        backgroundColor: "rgba(255,153,0,0.75)",
        hoverBackgroundColor: "rgba(255,153,0,1)",
        data: [272]
    },
    {
        label: "9/18/2016 - 9/24/2016",
        backgroundColor: "rgba(255,255,0,0.75)",
        hoverBackgroundColor: "rgba(255,255,0,1)",
        data: [250]
    },
    {
        label: "9/4/2016 - 9/10/2016",
        backgroundColor: "rgba(0,255,0,0.75)",
        hoverBackgroundColor: "rgba(0,255,0,1)",
        data: [232]
    },
    {
        label: "9/11/2016 - 9/17/2016",
        backgroundColor: "rgba(0,0,255,0.75)",
        hoverBackgroundColor: "rgba(0,0,255,1)",
        data: [244]
    }]
};

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

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

看起来像这样:

enter image description here

我想要做的是在最后一个条形图(蓝色条形图案)上方添加一个标签,其中前一个/第四个条目与该条形图之间的百分比差异。在这种情况下,该值应为“+ 5.2%”,以便它看起来像这样:

enter image description here

我认为这需要一个afterDraw()事件的registring,但它应该看起来的细节是超出我的。

更新

如果我将此添加到建议的代码中:

if (chartInstance.id !== 2) return; // affect this one only

在上下文中:

afterDraw: function (chartInstance) {
    if (chartInstance.id !== 2) return; // affect this one only
    // We get the canvas context
    var ctx = chartInstance.chart.ctx;

...结果比没有它好一点(这会破坏我的第一个(馅饼)图表并完全抹掉接下来的两个(包括这里讨论的那个):

enter image description here

正如你所看到的那样,饼图仍然被剔除,并且两个条形图中的值都缩小了,好像一个吃人的部落已经在他们身上犯下了诡计。并且,在最后一栏上没有增值。

1 个答案:

答案 0 :(得分:1)

首先,您正确地考虑将afterDraw事件与plugin一起使用,我理解在所有数据和选项中找到我们真正想要的内容可能会非常混乱。

然而,遵循一个可以帮助您完成所需工作的插件:

var myPlugin = {
    afterDraw: function(chartInstance) {
        // We get the canvas context
        var ctx = chartInstance.chart.ctx;

        // And set all the properties we need
        ctx.font = Chart.helpers.fontString(14, 'bold', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';
        ctx.fillStyle = '#666';

        // We get the number of datasets we have in your chart
        var numOfDatasets = chartInstance.config.data.datasets.length;

        // For every dataset in our chart ...
        chartInstance.data.datasets.forEach(function(dataset) {

            // If it is not the last dataset, we return now (no action at all)
            if (dataset._meta[0].controller.index != numOfDatasets - 1) return;

            // For every data in the dataset ...
            for (var i = 0; i < dataset.data.length; i++) {

                // We get the previous dataset (to compare later)
                var previousDataset = chartInstance.config.data.datasets[dataset._meta[0].controller.index - 1];
                // And get the model of the current value
                var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;

                // We calculate the percentage difference with the previous
                var value = ((dataset.data[i] - previousDataset.data[i]) / previousDataset.data[i]) * 100;

                // And write it with a "%" symbol
                // The ternary adds a "+" symbol if it is a positive value
                ctx.fillText((value > 0 ? "+" : "") + value.toFixed(1) + "%", model.x, model.y);
            }
        });
    }
};

Chart.pluginService.register(myPlugin);

<小时/> 您可以看到此代码正常工作on this jsFiddle,结果如下:

enter image description here