how to hide 0 value on Yaxis in Chart.js with negative values

7.3k views Asked by At

I have create one bar chart with negative values using chart.js. Now i dont want to show 0 (zero) value on Y axis.

I google lot of thing but there is no luck for me.

i tried below properties as well.

ticks: {
                beginAtZero: false
            }

scaleStartValue: -20, scaleStepWidth: 20, scaleSteps: 3, scaleBeginAtZero: false,

but i didnt get success.

check below image, I have mention what is my expected result.

enter image description here

1

There are 1 answers

1
ɢʀᴜɴᴛ On BEST ANSWER

This can be achieved using the following y-axis ticks callback function :

callback: function(value, index) {
   if (value !== 0) return value + '%';
}

or - " change 0 value to 100% " :

callback: function(value, index) {
   if (value === 0) return 100 + '%';
   else return value + '%';
}

DEMO

var chart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
      datasets: [{
         label: 'BAR',
         data: [50, 20, -60, 55, -35],
         backgroundColor: 'rgba(0, 119, 290, 0.2)',
         borderColor: 'rgba(0, 119, 290, 0.6)',
         borderWidth: 2
      }]
   },
   options: {
      scales: {
         yAxes: [{
            ticks: {
               stepSize: 50,
               callback: function(value, index) {
                  if (value !== 0) return value + '%';
                  /* OR *
                  if (value === 0) return 100 + '%';
                  else return value + '%'; */
               }
            }
         }]
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>