Chartjs-Angular – ChartJS – Bar chart – First label is not showing in X axis

0πŸ‘

βœ…

One possible solution is to set the time.unit to "month" and use
ticks.callback to invalidate (return '') all but the first label for each year.

Here’s a non-react snippet that illustrates this idea:

const nPoints = 366,
    t0 = Date.now()-366*24*3600*1000,
    dt = 24*3600*1000;
const ctx = document.getElementById('canvasChart').getContext("2d");

let data = Array.from(
    {length: nPoints},
    (_, i)=>({
        datetime: t0 + dt*i,
        value: 10+4*Math.sin(i*Math.PI*3/nPoints)+
            3*Math.random() + (Math.random() < 0.05 ? 5*Math.random() : 0)
    })
);

const yearsWithLabel = [];
const config = {
    type: 'bar',
    data: {
        datasets:[{
            data,
            borderWidth: 1
        }]
    },
    options: {
        parsing: {
            xAxisKey: 'datetime',
            yAxisKey: 'value'
        },
        scales:{
            x:{
                type: 'time',
                grid:{
                    display: false
                },
                ticks:{
                    maxRotation: 0,
                    callback(val, index){
                        if(index === 0){
                            yearsWithLabel.splice(0);
                        }
                        const date = new Date(val),
                            yr = date.getFullYear();
                        if(yearsWithLabel.includes(yr)){
                            // if there's already a label for this year
                            return '';
                        }
                        yearsWithLabel.push(yr);
                        // you may want to add the month, otherwise one may think
                        // the interval between the labels 2022 and 2023 is one year:
                        // return date.toLocaleDateString(undefined, {year: 'numeric', month: "short"})
                        return date.toLocaleDateString(undefined, {year: 'numeric'})
                    }
                },
                time: {
                    unit: 'month',
                }
            }
        },
        plugins: {
            legend:{
                display: false
            }
        }
    },
};
new Chart(ctx, config);
<div style="width:90vw;height:90vh">
<canvas id="canvasChart" ></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns"></script>

Leave a comment