Chartjs-Something similar to grace available in the latest chartJs for ChartJs 2.9.3

0👍

You can use a custom plugin for this, if I understand the grace correctly this is how its supposed to work, if not you might need to tweak the calculations a bit

Example:

var options = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 20, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    plugins: {
      customScale: {
        grace: '100%',
        // grace: 40
      }
    }
  },
  plugins: [{
    id: "customScale",
    beforeLayout: (chart, options, c) => {
      let max = Number.MIN_VALUE;
      let min = Number.MAX_VALUE
      let grace = options.grace || 0

      chart.data.datasets.forEach((dataset) => {
        max = Math.max(max, Math.max(...dataset.data));
        min = Math.min(min, Math.min(...dataset.data))
      })

      if (typeof grace === 'string' && grace.includes('%')) {
        grace = Number(grace.replace('%', '')) / 100

        chart.options.scales.yAxes.forEach((axe) => {
          axe.ticks.suggestedMax = max + (max * grace)
          axe.ticks.suggestedMin = min - (min * grace)
        })

      } else if (typeof grace === 'number') {

        chart.options.scales.yAxes.forEach((axe) => {
          axe.ticks.suggestedMax = max + grace
          axe.ticks.suggestedMin = min - grace
        })

      }

    }
  }]
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</body>

Fiddle: https://jsfiddle.net/Leelenaleee/7vfg29wL/49/

Leave a comment