[Chartjs]-How can I hide missing or null bars in a Chart.js bar chart?

0👍

You simply can fix all issues, if you sort the data sets (array sort function documentation ), on the year property.
Since "misalignment" causes issues, of the datasets.

Here a demo:

const data = [
    { year: 2010, count: 10 },
    { year: 2013, count: 15 },
    { year: 2110, count: null },
    { year: 5464, count: 4 },
    { year: 564, count: 3 }, 
];

const data2 = [
    { year: 564, count: 30 },
    { year: 2010, count: null },
    { year: 2110, count: 3 },
    { year: 5464, count: 3 },
];

let years =  [ ...data.map( x => x.year), ...data2.map( x => x.year)];

years.forEach((year) => {
    if(!data.find( x => x.year == year)){
        data.push({ year })
    }
    if(!data2.find( x => x.year == year)){
        data2.push({ year })
    }
});

data.sort((a,b) => a.year - b.year);
data2.sort((a,b) => a.year - b.year);

const config =  {
        type: 'bar',
        data: {
            datasets: [
                {
                    label: 'Set 1',
                    data: data.map(row => ({ x: row.year, y: row.count })),
                    backgroundColor: '#00ff00'
                },
                {
                    label: 'Set 2',
                    data: data2.map(row => ({ x: row.year, y: row.count })),
                    backgroundColor: '#ff0000'
                },
            ],
            xLabels: Array.from(new Set([...data, ...data2].map(row => row.year))).sort((a, b) => a-b)
        },
        options: {
            skipNull: true,
            responsive: true
        }
    };

new Chart(
    document.getElementById('chart'),
    config
);
<script src="//cdn.jsdelivr.net/npm/chart.js"></script>  

<div class="chart" style="height:184px; width:350px;">
    <canvas  id="chart" ></canvas>
</div>

Update: You just need to match the Dataset entries, of both dataset.

In the example above I do it with looping through all year of both dataset and add the missing once in the respective array. There is probably a more efficient way, but I just wanted to showcase the reason for the problem, and a solution.

Leave a comment