You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将ChartJS水平条形图X轴的小数改为整数?

Fixing Horizontal Bar Chart X-Axis to Show Only Integers in Chart.js

Got it, let's get that X-axis displaying whole numbers instead of decimals—perfect for your current data (0 and 1) and future updates too!

The issue here is that Chart.js automatically generates scale ticks based on available space, which can lead to decimal values when your dataset range is small. To override this, you just need to add a scales configuration to your chart options, targeting the X-axis (since it's a horizontal bar chart, the X-axis is the numerical axis).

Here's your updated code with the fix included:

new Chart(document.getElementById("bar-chart-grouped_E09"), {
  type: 'horizontalBar',
  data: {
    labels: E09_labels,
    datasets: [
      { label: "Male", backgroundColor: "#3e95cd", data: E09_M_values },
      { label: "Female", backgroundColor: "#8e5ea2", data: E09_F_values }
    ]
  },
  options: {
    title: {
      display: true,
      text: 'Drug or chemical induced diabetes mellitus'
    },
    // Add this scale configuration to force integer ticks
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero: true, // Ensures the axis starts at 0 (standard for bar charts)
          stepSize: 1, // Sets tick interval to 1, so only whole numbers appear
          // Optional: Extra safety filter to ignore non-integer ticks
          callback: function(value) {
            if (Number.isInteger(value)) {
              return value;
            }
          }
        }
      }]
    }
  }
});

Quick breakdown of the key settings:

  • beginAtZero: Keeps your chart anchored at 0, making your small dataset (0 and 1) visually clear and accurate.
  • stepSize: 1: Forces the axis to only show ticks at whole-number intervals. This will automatically adapt as you add more integer data later.
  • The callback function: An extra layer of protection to ensure only integer values are displayed, just in case Chart.js tries to generate decimal ticks despite the stepSize rule.

This setup will keep your chart looking clean and aligned with your integer-based data both now and as you expand your dataset.

内容的提问来源于stack exchange,提问作者Bejita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:33:44