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

如何调整Chart.js柱状图的柱子宽度使其更细?

解决Chart.js柱状图柱子过宽的问题

当分类数量较少(比如你这里仅2个分类)时,Chart.js默认会让柱子占满对应分类的可用空间,导致柱子过宽。你可以通过以下两种方式调整:

方式一:用比例参数灵活控制

在图表配置中添加options.scales.x配置,通过barPercentage和categoryPercentage两个参数调整柱子宽度比例:

<body>
<div class="chart-container" style="position: relative; height:40vh; width:80vw">
  <canvas id="myChart" ></canvas>
</div> 
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.2/dist/chart.umd.min.js"></script>
<script>
  const ctx = document.getElementById('myChart');

  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['Males', 'Females'],
      datasets: [{
      label: 'Students Registrations by Gender',
      data: [<?php echo $maleCount; ?>, <?php echo $femaleCount; ?>],
      borderWidth: 1,
      backgroundColor: ['rgb(54, 162, 235)', 'rgb(255, 99, 132)' ]
      }] 
    },
    options: {
      scales: {
        x: {
          barPercentage: 0.4, // 柱子占自身分类宽度的比例(0-1区间,值越小柱子越细)
          categoryPercentage: 0.8 // 分类组占x轴对应位置可用空间的比例(0-1区间)
        }
      }
    }
  });
</script>
</body>
  • barPercentage:控制单根柱子相对于所在分类宽度的占比,比如设为0.4意味着柱子仅占分类宽度的40%
  • categoryPercentage:控制整个分类组(此处每个分类仅一根柱子)在x轴上的空间占比

方式二:固定柱子宽度

如果需要更精准的尺寸控制,可直接在dataset中设置barThickness为固定像素值:

datasets: [{
  // 其他配置保持不变
  barThickness: 50 // 将柱子宽度固定为50px,可按需调整数值
}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 04:57:08