Chart.js:如何移除水平堆叠条形图上下的额外内边距
移除ChartJS水平堆叠条形图上下的额外内边距
你遇到的上下红色内边距,本质是ChartJS为Y轴(水平条形图的索引轴)默认保留了标签空间和条形间距,即使隐藏了刻度、网格,这些默认布局规则依然生效。以下是针对性解决方法:
关键修改点
- 强制Y轴范围贴合单个条形:因为只有一个分类标签,直接设置Y轴的
min和max为-0.5和0.5,让轴的高度刚好覆盖条形。 - 消除条形内部padding:设置
barPercentage: 1和categoryPercentage: 1,让条形完全填充Y轴的可用空间。 - 统一布局负padding:为top和right也添加负padding,确保四周无多余空隙。
修改后的完整代码
JavaScript
let barChart = new Chart(document.getElementById("canvas"), { type: "bar", data: { labels: ["Bar"], datasets: [ { label: "Account 1", backgroundColor: "#3e95cd", pointRadius: 0, barPercentage: 1, categoryPercentage: 1, data: [{ x: [0, 10], y: "Bar" }], }, { label: "Account 2", backgroundColor: "#8e5ea2", pointRadius: 0, barPercentage: 1, categoryPercentage: 1, data: [{ x: [10, 15], y: "Bar" }], }, { label: "Account 3", backgroundColor: "#3cba9f", pointRadius: 0, barPercentage: 1, categoryPercentage: 1, data: [{ x: [15, 20], y: "Bar" }], }, ], }, options: { indexAxis: "y", responsive: true, maintainAspectRatio: false, layout: { padding: { left: -8, bottom: -8, top: -8, right: -8 }, }, scales: { y: { beginAtZero: true, stacked: true, border: { display: false, }, ticks: { display: false, }, grid: { display: false, }, min: -0.5, max: 0.5 }, x: { border: { display: false, }, ticks: { display: false, }, grid: { display: false, }, }, }, plugins: { legend: { display: false, }, tooltip: { enabled: false, }, }, }, })
CSS
.chart { background: red; }
HTML
<div class="chart"> <canvas class="chart__canvas" id="canvas"></canvas> </div> <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.4"></script>
效果说明
修改后,水平堆叠条形会完全贴合容器的上下左右边界,红色背景不会再从条形的上下露出,彻底消除了多余的内边距。
内容的提问来源于stack exchange,提问作者daniil sidorov
相关产品推荐
相关产品推荐

