Chart.js柱状图优化:添加记录间距并居中Design#2标签
解决Chart.js柱状图两组数据间距与子标签居中问题
需求说明:
- 在Design#1与Design#2两组柱状图之间添加明显间距
- 确保Design#2的子标签和Design#1一样,精准居中对应本组数据区域
效果参考:
修改思路
- 组间距实现:在两组数据标签之间插入空占位标签,配合x轴的
ticks.padding配置放大空隙,同时给空标签对应的数据设为0、背景透明,避免显示多余柱子 - 子标签居中修正:通过x轴的
getPixelForValue方法获取每组数据的中心位置,让子标签精准对齐本组柱状图的中间区域
修改后的完整代码
<canvas id="p-myChart" style="display: block; box-sizing: border-box; height: 450px; width:100% !important "></canvas> <script src="https://www.chartjs.org/dist/master/chart.umd.js"></script> <script> // setup const data = { // 在两组数据之间插入空标签作为间距占位 labels: ['LUT', 'DFFs', 'CLBs', 'BRAMs', 'DSPs', 'FLE', 'Metal', '', 'LUT', 'DFFs', 'CLBs', 'BRAMs', 'DSPs', 'FLE', 'Metal'], datasets: [{ label: 'Aligned With benchmark', // 空标签位置填0,不显示柱子 data: [1000, 750, 500, 250, 400, 950, 800, 0, 750, 450, 500, 600, 300, 200, 700], backgroundColor: 'rgb(255, 255, 255)', borderColor: 'rgba(0, 0, 0, 1)', borderWidth: 2 }, { label: 'name here', // 空标签位置填0,背景设为透明 data: [900, 650, 800, 450, 820, 750, 300, 0, 550, 250, 500, 700, 500, 100, 600], backgroundColor: [ 'rgba(36, 159, 93,1)', 'rgba(36, 159, 93, 1)', 'rgba(241, 180, 94, 1)', 'rgba(255, 0, 0, 1)', 'rgba(255, 0, 0, 1)', 'rgba(36, 159, 93, 1)', 'rgba(36, 159, 93, 1)', 'rgba(255,255,255,0)', 'rgba(248, 174, 71)', 'rgba(255, 0, 0, 1)', 'rgba(36, 159, 93, 1)', 'rgba(241, 180, 94, 1)', 'rgba(255, 0, 0, 1)', 'rgba(36, 159, 93, 1)', 'rgba(255, 0, 0, 1)' ], }, ] }; const subLabels = { id: 'subLabels', afterDatasetsDraw(chart, args, pluginOptions) { const { ctx, chartArea: { bottom }, scales: { x } } = chart; ctx.save(); // 计算每组数据的中心像素位置:第一组中心是第3个标签,第二组是第11个标签 const design1Center = x.getPixelForValue(3); const design2Center = x.getPixelForValue(11); subLabelText('Design#1', design1Center); subLabelText('Design#2', design2Center); function subLabelText(text, xPos) { ctx.font = '12px sans-serif'; ctx.fillStyle = 'rgba(0,0,0,1)'; ctx.textAlign = 'center'; ctx.fillText(text, xPos, bottom + 40); } } } // config const config = { type: 'bar', data, options: { plugins: { legend: { display: false } }, layout: { padding: { bottom: 50 // 增加底部内边距,避免子标签被截断 } }, scales: { y: { beginAtZero: true, ticks: { min: 0 } }, x: { barPercentage: 0.8, // 调整单根柱子的宽度占比 categoryPercentage: 0.9, // 调整每组柱子的整体宽度占比 ticks: { // 隐藏空标签的显示 callback: function(value) { return this.getLabelForValue(value) === '' ? '' : this.getLabelForValue(value); }, // 给空标签位置设置更大的左右内边距,放大组间距 padding: function(value) { return this.getLabelForValue(value) === '' ? 30 : 5; } } } } }, plugins: [subLabels] }; // 渲染图表 const myChart1 = new Chart( document.getElementById('p-myChart'), config ); </script>
内容的提问来源于stack exchange,提问作者shoaib
相关产品推荐
相关产品推荐

