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

React中Chart.js标签需取消45度旋转,改为段落式换行显示

解决Chart.js x轴标签自动换行问题

只设置maxRotation: 0无法实现自动换行,需要配合多个配置项调整,强制标签不旋转并自动换行:

  • 同时设置ticks.maxRotation和ticks.minRotation为0,彻底禁用标签旋转
  • 配置ticks.maxWidth指定标签的最大宽度,超出该宽度的内容会自动换行
  • 关闭ticks.autoSkip避免标签被自动隐藏,确保所有标签都显示
  • 若标签文本过长仍无法正常换行,可通过ticks.callback手动拆分文本为数组(Chart.js 3+支持数组形式的标签,自动按元素换行)

React项目中的代码示例(Chart.js 3+)

import { Line } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Tooltip, Legend } from 'chart.js';

// 注册必要的组件
ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Tooltip, Legend);

const chartOptions = {
  scales: {
    x: {
      ticks: {
        maxRotation: 0,
        minRotation: 0,
        maxWidth: 120, // 根据需求调整宽度
        autoSkip: false,
        // 可选:手动拆分超长标签
        callback: (label) => {
          // 按空格拆分,超过2个单词就换行
          const wordArr = label.split(' ');
          if (wordArr.length > 2) {
            return [wordArr.slice(0, 2).join(' '), wordArr.slice(2).join(' ')];
          }
          return label;
        }
      }
    }
  }
};

const chartData = {
  labels: ['月度销售数据汇总报告', '季度用户增长分析', '年度营收统计', '产品迭代效果追踪'],
  datasets: [{
    label: '核心指标',
    data: [42, 58, 33, 67],
    borderColor: '#2196F3',
    backgroundColor: 'rgba(33, 150, 243, 0.1)',
    tension: 0.2
  }]
};

export default function CustomLabelChart() {
  return <Line options={chartOptions} data={chartData} />;
}

针对Chart.js 2.x版本的适配

如果你的项目使用Chart.js 2.x,配置结构略有不同,x轴配置放在scales.xAxes数组中:

const chartOptions = {
  scales: {
    xAxes: [{
      ticks: {
        maxRotation: 0,
        minRotation: 0,
        maxWidth: 120,
        autoSkip: false,
        callback: (label) => {
          const wordArr = label.split(' ');
          return wordArr.length > 2 ? [wordArr.slice(0,2).join(' '), wordArr.slice(2).join(' ')] : label;
        }
      }
    }]
  }
};

另外,注意调整图表容器的高度,确保换行后的标签有足够空间显示,不会被截断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:40:40