How can i add a calculated value on top of the bars in Chart.js?

I am getting the data values on hover as desired:

enter image description here

...but I also want to add a value on top of each bar, something like this:

enter image description here

How can I grab calculated data and embed it within each bar?

My code is as follows:

HTML

<div class="graph_container">
    <canvas id="priceComplianceBarChart"></canvas>
</div>

JQUERY

    Chart.defaults.global.defaultFontFamily = "Georgia";

    var ctxBarChart = 
$("#priceComplianceBarChart").get(0).getContext("2d");
    var barChartData = {
        labels: ["Bix Produce", "Capitol City", "Charlies Portland", 
"Costa Fruit and Produce", "Get Fresh Sales", "Loffredo East", "Loffredo
West", "Paragon", "Piazza Produce"],
        datasets: [
            {
                label: "Price Compliant",
                backgroundColor: "rgba(34,139,34,0.5)",
                hoverBackgroundColor: "rgba(34,139,34,1)",
                data: [17724, 5565, 3806, 5925, 5721, 6635, 14080, 9027,
25553]
            },
            {
                label: "Non-Compliant",
                backgroundColor: "rgba(255, 0, 0, 0.5)",
                hoverBackgroundColor: "rgba(255, 0, 0, 1)",
                // The vals below have been multiplied by 10 (a 0
appended) so that the values are at least visible to the naked eye
                data: [170, 10, 180, 140, 30, 10, 50, 100, 10]
            }
        ]
    }

    var optionsBar = {
        scales: {
            xAxes: [
                {
                    stacked: true
                }
            ],
            yAxes: [
                {
                    stacked: true
                }
            ]
        },
        showInlineValues: true,
        centeredInllineValues: true,
        label: {
            font: {
                family: "Georgia"
            }
        }
    };

    var priceBarChart = new Chart(ctxBarChart, {
        type: 'horizontalBar',
        data: barChartData,
        options: optionsBar
    });
    priceBarChart.defaults.global.defaultFont = "Georgia";

UPDATE

Dekel: Your answer is pretty close - this is what I see with that code unchanged:

enter image description here

So not only does the value placed on the bar need to be further to the right, I need the hover data to appear as before (it's being truncated a little now, as you can see in the screenshot) and, instead of the two values displaying on each segment of the bar, a % value (which % the larger of the two values is of the combined value of both numbers).

Note: The same applies as to the other question (in fact, all my questions as long as I have points left): I will bountify them for the maximum number of points allowed (500).

UPDATE 2

By changing this code:

ctx.fillText(dataset.data[i], model.base + 10, model.y + 5);

...to this:

ctx.fillText("99.9%", model.base + 25, model.y + 6);

...I now see the number on the bar aligned right (but, of course, they are all bogus/mock values). The hover value is still truncated, though, and I don't need the value ("99.9%" now) repeated at the end of each bar.

Upvotes: 1

Views: 650

Answers (1)

Dekel
Dekel

Reputation: 62536

You can register a new function using the pluginService for the afterDraw:

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(dataset.data[i], model.base + 10, model.y+5);
            }
        });
    }
});

If you need to calculate something you can replace dataset.data[i] in ctx.fillText with the calculated data you have.

Upvotes: 2

Related Questions