JS新手求助:如何用Chart.js绘制嵌套字典数据图表?
使用Chart.js绘制分组柱状图处理嵌套字典数据
1. 数据转换
首先需要把你的嵌套字典转换成Chart.js能识别的格式:
- 提取所有技术名称(
tech_1、tech_2)作为X轴标签 - 提取所有证书名称作为数据集名称
- 为每个证书生成对应的数值数组,对应每个技术下的数值,没有的填0
2. 完整代码示例
<!-- 引入Chart.js --> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <!-- 图表容器 --> <div style="width: 80%; margin: 0 auto;"> <canvas id="certChart"></canvas> </div> <script> // 你的原始数据 const rawData = { "tech_1": { "cert_1": 1, "cert_2": 3 }, "tech_2": { "cert_3": 10, "cert_4": 5 } }; // 提取技术名称作为X轴标签 const techLabels = Object.keys(rawData); // 收集所有证书名称 const allCerts = new Set(); techLabels.forEach(tech => { Object.keys(rawData[tech]).forEach(cert => allCerts.add(cert)); }); const certNames = Array.from(allCerts); // 生成数据集数组 const datasets = certNames.map(cert => { const data = techLabels.map(tech => { // 如果当前技术有该证书,取数值,否则为0 return rawData[tech][cert] || 0; }); // 为每个数据集生成随机区分颜色 const color = `rgba(${Math.floor(Math.random()*255)}, ${Math.floor(Math.random()*255)}, ${Math.floor(Math.random()*255)}, 0.7)`; return { label: cert, data: data, backgroundColor: color, borderColor: color.replace('0.7', '1'), borderWidth: 1 }; }); // 初始化图表 const ctx = document.getElementById('certChart').getContext('2d'); new Chart(ctx, { type: 'bar', // 分组柱状图类型 data: { labels: techLabels, datasets: datasets }, options: { responsive: true, scales: { y: { beginAtZero: true, title: { display: true, text: '数量' } }, x: { title: { display: true, text: '技术类别' } } }, plugins: { legend: { position: 'top', }, title: { display: true, text: '各技术对应证书数量' } } } }); </script>
3. 代码说明
- 数据转换部分:通过
Object.keys提取技术和证书名称,用Set去重收集所有证书,然后遍历每个证书生成对应的数据数组 - 图表配置:使用
bar类型实现分组柱状效果,开启响应式适配不同容器,配置坐标轴标题和图表标题,每个数据集对应一个证书,自动生成区分颜色 - 如果需要堆叠柱状图效果,只需在
options的scales中添加:x: { stacked: true }, y: { stacked: true }
内容的提问来源于stack exchange,提问作者Jeremy
相关产品推荐
相关产品推荐

