您需要定义一个附加的yAxis
,其中除了堆叠的钢筋的labels
外不包含任何其他内容。我们将向每个数据集添加yAxisID
属性。这必须与标准scales.yAxes.id
轴的刻度属性category
相匹配。
yAxes: [{
labels: ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
},
{
id: 'yAxis1',
type: 'category',
offset: true,
gridLines: {
offsetGridLines: true
}
}
]
请查看下面的可运行代码。
var barChartData = {
labels: ["January", "February", "March"],
datasets: [{
label: "Dataset 1",
yAxisID: 'yAxis1',
backgroundColor: "#FF0000",
categoryPercentage: 1,
barPercentage: 0.8,
stack: "Stack 0",
data: [1, 2, 3],
},
{
label: "Dataset 2",
yAxisID: 'yAxis1',
backgroundColor: "#0000FF",
categoryPercentage: 1,
barPercentage: 0.8,
stack: "Stack 0",
data: [5, 4, 3],
},
{
label: "Dataset 3",
yAxisID: 'yAxis1',
backgroundColor: "#00CC00",
categoryPercentage: 1,
barPercentage: 0.8,
stack: "Stack 1",
data: [6, 5, 4],
},
{
label: "Dataset 4",
yAxisID: 'yAxis1',
backgroundColor: "#000000",
categoryPercentage: 1,
barPercentage: 0.8,
stack: "Stack 2",
data: [6, 5, 4],
}
]
};
new Chart('chart', {
type: "horizontalBar",
data: barChartData,
options: {
scales: {
yAxes: [{
labels: ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
},
{
id: 'yAxis1',
type: 'category',
offset: true,
gridLines: {
offsetGridLines: true
}
}
]
},
title: {
display: true,
text: "Chart.js Bar Chart - Stacked",
},
tooltips: {
mode: "index",
intersect: false,
},
responsive: true,
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart"></canvas>