CrazyDev
CrazyDev

Reputation: 157

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

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

Upvotes: 3

Views: 7622

Answers (2)

ktphuc1994
ktphuc1994

Reputation: 1

ChartJS v4 and react-chartjs-2 v5. For the x-axis, I used this systax:

options: {
  scales: {
    x: {
      ticks: {
        callback: function(val, index) {
          if (index === 0) return null; 
          return this.getLabelForValue(val);
        }
      }
    }
  }
}

From this document: Tick Configuration

Since the val and index are the same. So I have to use getLabelForValue to get the Tick label.

Upvotes: 0

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32859

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>

Upvotes: 5

Related Questions