Chartjs-Chart.js have the y-axis step from 20 to 1 (instead of 1 to 20)

0👍

Make sure not to display ticks on the first yAxis and add a second yAxis that display generated ticks in reverse order.

{
  ticks: {
    reverse: true,
    autoSkip: false,
    max: 1,
    min: 20
  },
  afterBuildTicks: (axis, ticks) => Array(20).fill().map((v,i) => i + 1).reverse()
}

Further you’ll have to define a tooltips.callback.label function to display proper values in the tooltips.

Please have a look at the runnable code snippet below.

const labels = ['A', 'B', 'C', 'D'];
const data = [12, 1, 8, 17];
const yTop = 1;
const yBottom = 20;

new Chart('myChart', {
  type: 'bar',
  data: {
    labels: labels,
    datasets: [{
      label: "My Dataset",
      data: data.map(v => yBottom + 1 - v),
      borderWidth: 3
    }]
  },
  options: {
    legend: {
      display: false
    },
    tooltips: {
      callbacks: {
        label: tooltipItem => data[tooltipItem.index]
      }
    },
    scales: {
      yAxes: [{
          ticks: {
            display: false,
            min: yTop,
            max: yBottom
          },
          gridLines: {
            drawTicks: false
          }
        },
        {
          ticks: {
            reverse: true,
            autoSkip: false,
            max: yTop,
            min: yBottom
          },
          afterBuildTicks: (axis, ticks) => Array(yBottom).fill().map((v, i) => i + 1).reverse()
        }
      ],
      xAxes: [{
        gridLines: {
          display: false
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="120"></canvas>

Leave a comment