SmartXAxis 智能判断流程
输入数据
计算 maxWidth & count
maxWidth ≤ 4 && count ≤ 8
场景1: 水平
不满足
继续↓
maxWidth ≤ 8 && count ≤ 12
场景2: 45°
不满足
继续↓
90° 仅当 maxWidth ≥ 50
场景4/6: 90°+截断6
不满足
继续↓
默认
场景3: 45°+截断8 ✓
SmartXAxis 完整工具函数
/** * 计算字符串的视觉宽度(中文×2,英文×1) */ function getVisualWidth(str) { let width = 0; for (let i = 0; i < str.length; i++) { const charCode = str.charCodeAt(i); if (charCode >= 0x4E00 && charCode <= 0x9FFF || charCode >= 0x3000 && charCode <= 0x303F || charCode >= 0xFF00 && charCode <= 0xFFEF) { width += 2; // 中文、全角字符 } else { width += 1; // 英文、数字 } } return width; } /** * SmartXAxis - 智能X轴配置生成器 */ const SmartXAxis = { getConfig(data, xField, options = {}) { const { maxTruncate = 8, // 45°截断长度 minTruncate = 6, // 90°截断长度 } = options; const maxWidth = Math.max(...data.map(d => getVisualWidth(String(d[xField] || '')) )); const count = data.length; let rotate, truncateAt; if (maxWidth <= 4 && count <= 8) { rotate = 0; // 水平 truncateAt = null; } else if (maxWidth <= 8 && count <= 12) { rotate = -Math.PI / 4; // 45°不截断 truncateAt = null; } else if (maxWidth >= 50) { rotate = -Math.PI / 2; // 仅超长文字用 90° truncateAt = minTruncate; } else { rotate = -Math.PI / 4; // 多数据项统一 45°+截断 truncateAt = count >= 15 ? minTruncate : maxTruncate; } return { label: { autoRotate: false, rotate, formatter: (text) => { const str = String(text || ''); if (truncateAt && str.length > truncateAt) { return str.substring(0, truncateAt) + '...'; } return str; }, style: { fontSize: 11, fill: '#1D1D1F', textAlign: rotate === 0 ? 'center' : 'end', }, }, }; }, };
产品销量排行 - 完整业务图表示例 SmartXAxis 自动配置
24年12月各产品销售额、完成率、流量及进店量
数据源: 销售流水, 销售指标表
按 产品名称 × 分组
日期: 2024.12
万元
销售额
总计:销售额 -,平均 -,最高 -
在项目中使用 SmartXAxis

基本用法

import { Column } from '@ant-design/charts'; const config = { data, xField: 'product', yField: 'value', // 一行代码自动配置X轴 xAxis: SmartXAxis.getConfig(data, 'product'), };

自定义参数

// 自定义截断长度和阈值 xAxis: SmartXAxis.getConfig(data, 'product', { maxTruncate: 10, // 45°截断10字符 minTruncate: 8, // 90°截断8字符 manyItemThreshold: 20, // 20项触发90° })
完整图表应包含的元素
元素 位置 说明
标题 卡片头部 简洁描述图表内容
元信息 标题下方 数据源、筛选条件、时间范围等
Y轴单位 左上角 如"万元"、"%"等
图例 右上角 多系列时显示颜色对应
数据标签 柱体顶部 可选,显示具体数值
X轴标签 底部 智能处理旋转和截断
汇总栏 底部 显示总计、平均等统计数据