4

i have built a chart using chartjs. I'm trying to remove those data value that is zero from the chart. I wrote a function to display only value that is non-zero but it doesn't seem to work. Can anyone help?

Below is my Javascript

var ctx = document.getElementById('myChart2').getContext('2d');
            var myChart = new Chart(ctx, {
                type:<?php echo $chartype; ?>,
                data : {
                  labels: [<?php echo $datelist_2; ?>], <!--label name->
                  datasets: [
                      { 
                        label: "Sales",
                        data: [<?php echo $atlasdata2; ?>],
                        backgroundColor: 'rgb(248, 108, 108, 0.6)'
                      }                   
                      ]
                },
                .......
                .......
                .......
                      plugins: {
                              datalabels: {
                                 display: true,
                                 align: 'center',
                                 anchor: 'center',
                                 formatter: function(value, index, values) {
                                     if(value != 0){
                                         value = value.toString();
                                         value = value.split(/(?=(?:...)*$)/);
                                         value = value.join(',');
                                         return value;
                                     }
                                    }
                              }
                           }
                    }

                });

How my chart looks like currently?

Honestman
  • 177
  • 1
  • 1
  • 12

1 Answers1

12

Finally solve myself. its a silly answer. I need to add an else statement in order to make the zero disappear.

 plugins: {
            datalabels: {
                display: true,
                align: 'center',
                anchor: 'center',
                formatter: function(value, index, values) {
                            if(value >0 ){
                                value = value.toString();
                                value = value.split(/(?=(?:...)*$)/);
                                value = value.join(',');
                                return value;
                            }else{
                                value = "";
                                return value;
                            }
                        }
                    }
             }
Honestman
  • 177
  • 1
  • 1
  • 12
  • 4
    I found that when using colored backgrounds returning an empty string still rendered a small colored box. Maybe consider returning `null` as that makes the box disappear. – ethergeist Jul 13 '21 at 07:00
  • If you only need to hide 0 values `formatter: function (value, context) { return value || null; },` – Patronaut Feb 17 '22 at 12:41