Chartjs-How to properly render Chartjs with big difference between bars data?

0👍

You can define the yAxis as a logarithmic cartesian axis as shown in the runnable code snippet below.

new Chart("chart", {
  type: "bar",
  data: {
    labels: ['A', 'B', 'C', 'D'],
    datasets: [{
      label: "My Dataset",
      data: [50, 11780, 220855, 581358],
      backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)"],
      borderColor: ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)"],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        type: 'logarithmic',
        ticks: {
          userCallback: (value, index) => {
            const remain = value / (Math.pow(10, Math.floor(Chart.helpers.log10(value))));
            if (remain == 1 || remain == 2 || remain == 5 || index == 0) {
              return value.toLocaleString();
            }
            return '';
          }
        },
        gridLines: {
          display: false
        }        
      }],
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="180"></canvas>

Leave a comment