如何拆分图表X轴labels为独立分类?费用追踪应用图表异常求助
问题解决:费用分类图表合并及环形/饼图无法显示
核心问题
你的代码在调用renderChart时错误地将labels和data包裹在了额外的数组中,导致Chart.js无法识别多个分类,进而出现:
- 柱状图将三个分类合并为单根柱子
- 环形图/饼图因数据格式错误无法渲染
修正步骤
- 修复数据传递错误:去掉
renderChart([data], [labels])中的外层数组,直接传递data和labels - 支持多种图表类型:将图表类型改为可配置参数,方便切换柱状、环形、饼图
修正后的完整代码
const renderChart = (data, labels, chartType = 'bar') => { const ctx = document.getElementById('myChart').getContext('2d'); // 先销毁已有图表实例,避免重复渲染报错 if (window.myChartInstance) { window.myChartInstance.destroy(); } window.myChartInstance = new Chart(ctx, { type: chartType, data: { labels: labels, datasets: [{ label: '当月费用', data: data, backgroundColor: [ '#FF6384', '#36A2EB', '#FFCE56' ], // 为环形/饼图添加分类颜色 borderColor: [ '#FF6384', '#36A2EB', '#FFCE56' ], borderWidth: 1 }] }, options: { borderWidth: 10, borderRadius: 2, hoverBorderWidth: 0, plugins: { legend: { display: chartType !== 'bar' // 环形/饼图显示图例,柱状图隐藏 }, }, }, }); } const getChartData = () => { console.log("fetching") fetch('expense_category_summary') .then((res) => res.json()) .then((results) => { console.log("results", results); const category_data = results.expense_category_data; const [labels, data] = [ Object.keys(category_data), Object.values(category_data), ]; // 直接传递data和labels,无需外层数组 renderChart(data, labels); // 如果需要渲染环形图,调用:renderChart(data, labels, 'doughnut') // 如果需要渲染饼图,调用:renderChart(data, labels, 'pie') }); }; // 替换document.onload为DOMContentLoaded,确保DOM加载完成后执行 document.addEventListener('DOMContentLoaded', getChartData);
关键说明
- 数据格式修正:Chart.js要求
labels是一维字符串数组,data是一维数值数组,之前的双层数组会被识别为单个数据系列的单个数据点 - 图表实例管理:添加了实例销毁逻辑,避免多次渲染时出现Canvas已被占用的错误
- 类型适配:根据图表类型自动控制图例显示,并为环形/饼图添加了分类颜色,提升可视化效果
内容的提问来源于stack exchange,提问作者RAzOR
相关产品推荐
相关产品推荐

