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

Chart.js设置横向条形图stepSize为1时图表轴键异常问题排查

问题排查:Chart.js横向条形图x轴stepSize设置后轴标签异常

问题描述

使用Chart.js创建横向条形图时,设置x轴刻度stepSize: 1后图表出现异常:x轴与y轴的标签均显示为name字段内容,不符合“y轴显示分类名称、x轴显示数值刻度”的预期效果。

数据示例

[
  {
    "name": "Finanzdienstleistungen, Finanzprodukte ...",
    "id": 1,
    "value": 80
  },
  {
    "name": "Urheberrechtsverletzungen und Wettbewerbs...",
    "id": 2,
    "value": 0
  },
  {
    "name": "Produktsicherheit und -konformität",
    "id": 3,
    "value": 0
  },
  {
    "name": "Verkehrssicherheit und Umweltschutz",
    "id": 4,
    "value": 0
  }
]

原问题代码

const ctx = document.getElementById('myChart');
const data = JSON.parse(document.getElementById('data-statistic').textContent);
let chart = new Chart(ctx, {
  type: 'bar',
  data: {
    datasets: [{
      label: 'Incidents',
      data: data,
      indexAxis: 'y',
      backgroundColor: [
        'rgb(255, 99, 132)',
        'rgb(54, 162, 235)',
        'rgb(255, 205, 86)'
      ],
      borderWidth: 1,
    }]
  },
  options:{
    parsing: {
      yAxisKey: 'name',
      xAxisKey: 'value'
    },
    scales: {
      x: {
         ticks: {
            type: 'value',
            stepSize: 1
         }
      }
   },
  }
});

问题原因

  1. 错误配置type: 'value':在ticks层级设置type: 'value'会强制Chart.js错误解析x轴数据源,覆盖了parsing中xAxisKey: 'value'的配置,导致x轴误将name字段作为数据来源。
  2. stepSize位置错误:stepSize是轴(scale)的直接配置项,而非ticks子配置项,放在ticks里无法生效,反而触发解析逻辑混乱。

修正方案

移除ticks中的type: 'value',并将stepSize移到scales.x的根层级:

const ctx = document.getElementById('myChart');
const data = JSON.parse(document.getElementById('data-statistic').textContent);
let chart = new Chart(ctx, {
  type: 'bar',
  data: {
    datasets: [{
      label: 'Incidents',
      data: data,
      indexAxis: 'y',
      backgroundColor: [
        'rgb(255, 99, 132)',
        'rgb(54, 162, 235)',
        'rgb(255, 205, 86)'
      ],
      borderWidth: 1,
    }]
  },
  options:{
    parsing: {
      yAxisKey: 'name',
      xAxisKey: 'value'
    },
    scales: {
      x: {
        stepSize: 1, // 移到轴的根层级
        ticks: {
          // 移除无效的type配置
        }
      }
   },
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 08:56:09