1

I have a dataset with very big numbers (billion) and small numbers (millions). When I plot it on a horizontal bar chart the low number seem to almost disappear. I have tried different ways of scaling but still could not find a solution.

export const options = {
  indexAxis: "y" as const,
  elements: {
    bar: {
      borderWidth: 2
    }
  },
  responsive: true,
  plugins: {
    legend: {
      position: "right" as const
    },
    title: {
      display: true,
      text: "Chart.js Horizontal Bar Chart"
    }
  },
  scales: {
    // min: 0,
    // max: 800000000000,
    // stepSize: 1000000000,
    x: {
      ticks: {
        // beginAtZero: false,
        // stepSize: 1000000,
      }
    }
  }
};

const labels = ["January", "February", "March", "April"];

export const data = {
  labels,
  datasets: [
    {
      label: "Dataset 1",
      data: [440000000000, 3000000000, 1000000000, 880147000],
      borderColor: "rgb(255, 99, 132)",
      backgroundColor: "rgba(255, 99, 132, 0.5)"
    }
  ]
};

export function App() {
  return <Bar options={options} data={data} />;
}

Link to sandbox https://codesandbox.io/s/new-dawn-hssfmf?file=/App.tsx:314-1165

How can I scale properly such that the bars for the small numbers are shown properly and are not almost hidden ?

Tee
  • 385
  • 3
  • 14

1 Answers1

1

You can use a logarithmic scale:

const options = {
  type: 'bar',
  data: {
    labels: ["January", "February", "March", "April"],
    datasets: [{
      label: '# of Votes',
      data: [440000000000, 3000000000, 1000000000, 880147000],
      backgroundColor: 'pink'
    }]
  },
  options: {
    indexAxis: 'y',
    scales: {
      x: {
        type: 'logarithmic'
      }
    }
  }
}

const 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/3.9.1/chart.js"></script>
  </script>
</body>
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69
  • thanks for the answer. I get the error "logarithmic is not a registered scale" when I added this to my code. Any idea why I may have gotten this error ? – Tee Aug 31 '22 at 11:55
  • I fixed it now. I needed to import and register the LogarithmicScale. – Tee Aug 31 '22 at 12:01