[Chartjs]-Chartjs polararea ticks label getting overlapped

1👍

I searched all options and it appears there’s no simple way to this. Except the way that is too simple – adding space characters in front of the label text in options.scales.r.ticks.callback.

The solution below is based on creating a custom axis class, deriving from RadialLinearScale and overriding only its drawLabels to translate the canvas context before the standard label drawing operation and restoring it for all other uses. I don’t think these methods are documented, but can be identified quite easily in the high quality source code of charts.js

I also adjusted the option object keys for some of the original options, to work in this environment.

class TranslatedLabelsScale extends Chart.RadialLinearScale{
    static id = 'linearRadialWithLabelTranslations';
    drawLabels(){
        const translation = this.options.ticks?.labelTranslation || {};
        this.ctx.save();
        this.ctx.translate(translation.x || 0, translation.y || 0);
        super.drawLabels();
        this.ctx.restore();
    }
}
Chart.register(TranslatedLabelsScale);

var ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
    type: 'polarArea',
    data: {
        labels: ['Label 1', 'Label 2', 'Label 3', 'Label 4', 'Label 5'],
        datasets: [{
            data: [10, 20, 30, 40, 50],
            backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF']
        }]
    },
    options: {
        maintainAspectRatio: false,
        scales: {
            r: {
                //startAngle: 20,
                type: 'linearRadialWithLabelTranslations',
                ticks: {
                    padding: 10,
                    fontSize: 14,
                    color: '#000',
                    fontStyle: 'normal',
                    labelTranslation: {x: 20, y: 0},
                    z: 10,
                    backdropColor: 'rgba(255, 255, 255, 0)',
                    fontFamily: 'Helvetica Neue,Helvetica,Arial,sans-serif',
                    callback: function(value, index, values){
                        // poor man's solution: return '     '+value + '°'
                        return value + '°'; // Add a degree symbol to the tick labels
                    }
                }
            }
        }, // other chart configurations...
    }
});
<canvas id="myChart" width="350" height="400"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

Leave a comment