Chartjs-How can I move a label left, paint it black, or remove it (Chart.JS)?

1๐Ÿ‘

โœ…

1st solution: Move to the left

In your plugin, set the context textAlign property to right if it is the second dataset:

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;

        // If it is the second dataset (red color) ..
        if (dataset._meta[0].controller.index== 1) {
            // .. align to the right
            ctx.textAlign ="right";
            // .. and write it at the right bound of the chart
            ctx.fillText(parseFloat(dataset.data[i]).toFixed(2) + "%", (model.x - 2), (model.y + model.height / 3));

           // This looks like it has been moved a bit to the left
        }

        // Else ..
        else {
            // .. write as usual
            ctx.fillText(parseFloat(dataset.data[i]).toFixed(2) + "%", ((model.base + model.x) / 2), (model.y + model.height / 3));
        }
    }
});

Check the result on this jsFiddle.


2nd solution: Put the text in black

In your plugin, set the context fillStyle property to the color you want (#000 for instance):

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';

    // Here:
    ctx.fillStyle = "#000";

    chartInstance.data.datasets.forEach(function(dataset) {
        // ...
    });
});

Check the result on this jsFiddle.


3rd solution: Remove it, pure and simple

Add a condition in your plugin to check which dataset you are currently working on:

chartInstance.data.datasets.forEach(function(dataset) {
    for (var i = 0; i < dataset.data.length; i++) {

        // If it is the second dataset (red color), we break out of the loop
        if (dataset._meta[0].controller.index == 1) break;

        var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;

        ctx.fillText(parseFloat(dataset.data[i]).toFixed(2) + "%", ((model.base + model.x) / 2), (model.y + model.height / 3));
    }
});

Check the result on this jsFiddle.

Leave a comment