[Chartjs]-Chart.JS: How can I only display data labels when the bar width is big enough for the text?

2👍

If the graph isn’t changing size dynamically you could obtain the width of a bar after creating the chart instance with

var width = myChart.getDatasetMeta(0).data[0]._model.width;

and rewrite your formatter to check if the text width does not exceed bar’s width

formatter: function (value, ctx) {
    function getTextWidth(text, font) {
        // re-use canvas object for better performance
        var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
        var context = canvas.getContext("2d");
        context.font = font;
        var metrics = context.measureText(text);
        return metrics.width;
    }
    return getTextWidth(value + "kWh") > width ? "" : value + "kWh";
}

Please take a note of the fact that i ignored the font in the example before so you would have to extract it manually if any changes were made.

You could perhaps even write a plugin that would write into the var width variable before the render

plugins: [
    ChartDataLabels,
    {
        beforeRender: (myChart) => { width = myChart.getDatasetMeta(0).data[1]._model.width;}
    }
],

1👍

The solution from Krzysztof Krzeszewski works. However, I had to slightly adjust it and add some checks for 'undefined' in my case:

if (typeof chart !== 'undefined') {
    let datasetData = chart.getDatasetMeta(0);

    if (datasetData !== 'undefined') {
        if (datasetData.data.length > 0) {
            barWidth = chart.getDatasetMeta(0).data[0]._model.width;
        }
    }
}

Leave a comment