How to change nan values to 0 in chart.js?

Member

by adan , in category: Javascript , 2 months ago

How to change nan values to 0 in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 2 months ago

@adan 

To change NaN (Not a Number) values to 0 in Chart.js, you can use the "ticks" option in the configuration object of your chart. Specifically, you can use the "min" and "max" properties within the "scales" object to set a minimum and maximum value for your y-axis.


Here's an example of how you can change NaN values to 0 in Chart.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'Sales',
            data: [5, NaN, 8, NaN, 10, 12, NaN],
            backgroundColor: 'rgba(54, 162, 235, 0.2)',
            borderColor: 'rgba(54, 162, 235, 1)',
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: {
                ticks: {
                    min: 0,
                    callback: function(value, index, values) {
                        return isNaN(value) ? 0 : value;
                    }
                }
            }
        }
    }
});


In this example, the "min" property inside the "ticks" object of the y-axis scales is set to 0. Additionally, the "callback" function is used to check if the tick value is NaN. If it is NaN, the function returns 0 instead. This way, any NaN values in the dataset will be displayed as 0 on the chart.