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

Angular12使用Chart.js开发条形图调整宽度时barPercentage配置失效怎么办

Chart.js 条形宽度调整解决方法

你需要的barPercentage: 0.4配置和已有的categoryPercentage为同层级参数,直接放在options.datasets.bar对象中即可全局生效,修改后的完整代码如下:

var myChart = new Chart('myChart', {
      type: 'bar',
      data: {
        labels: this.labels,
        datasets: [
          {
            data: this.data,
            backgroundColor: [' rgba(148, 180, 214,0.4)', 'rgba(239, 83, 80,0.4)', 'rgba(102, 187, 106,0.4)'],
            borderColor: [' #93b3d6', '#ef5350', '#66bb6a'],borderWidth: 1
          },
        ],
      },
      options: {
        plugins: {
          legend: {
            display: false,
          },
        },
        responsive: true,
        maintainAspectRatio: true,
        datasets: {
          bar: {
            categoryPercentage: 0.95,
            barPercentage: 0.4 // 新增的条形宽度控制参数
          }
        },
        scales: {
          y: {
            title: {
              display: true,
              text: 'Count',
            },
          },
          x: {
            title: {
              display: false,
              text: 'Total Count',
            },
          },
        },
      },
    });

可选配置规则

  • 全局生效:上述放在options.datasets.bar下的配置会作用于当前图表所有条形数据集
  • 单数据集生效:如果仅需要调整特定条形的宽度,可以直接把参数写在对应dataset的配置对象中,示例如下:
datasets: [
  {
    data: this.data,
    barPercentage: 0.4, // 仅对当前数据集生效
    backgroundColor: [' rgba(148, 180, 214,0.4)', 'rgba(239, 83, 80,0.4)', 'rgba(102, 187, 106,0.4)'],
    borderColor: [' #93b3d6', '#ef5350', '#66bb6a'],
    borderWidth: 1
  }
]

参数逻辑说明:categoryPercentage控制每个分类轴区间的总可用宽度占比,barPercentage控制单条条形在分类可用区间内的宽度占比,两个参数数值越小,最终显示的条形宽度越窄。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:15:03