我试图获得一个堆叠条形图,两个条形图在x轴上共享一个相邻的标签,但我在获得第二个条形图显示时遇到问题-目前它位于第一个条形图下方(如果您隐藏2021值,您将看到2022条形图将出现):
var barChartData = {
labels: ["January", "February"],
datasets: [{
data: [10, 20],
label: '2021',
backgroundColor: "#ffe100",
yAxisId: 'y-stacked',
}, {
data: [15, 30],
label: '2021 Total',
backgroundColor: "#ee0000",
yAxisId: 'y-stacked',
}, {
data: [6, 19],
label: '2022 YTD',
backgroundColor: "#555555",
}]
};
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
title: {
display: true,
text: "Chart.js Bar Chart - Stacked"
},
tooltips: {
mode: 'label'
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: false,
ticks: {
beginAtZero: true,
}
}, {
id: "y-stacked",
stacked: true,
display: false,
ticks: {
beginAtZero: true,
min: 0,
},
type: 'linear'
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.js"></script>
<div style="width: 100%">
<canvas id="canvas"></canvas>
</div>
有什么办法可以让2022酒吧在2021酒吧旁边显示吗?
我已经尝试添加另一个x轴并将x轴堆栈的值更改为false,但这只是解除了所有三个条的堆栈并将它们放在彼此旁边
你可以在数据集上使用堆叠属性你不需要多个轴
var barChartData = {
labels: ["January", "February"],
datasets: [{
data: [10, 20],
label: '2021',
backgroundColor: "#ffe100",
stack: 'stack 1',
}, {
data: [15, 30],
label: '2021 Total',
backgroundColor: "#ee0000",
stack: 'stack 1',
}, {
data: [6, 19],
label: '2022 YTD',
backgroundColor: "#555555",
stack: 'stack 2',
}]
};
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
title: {
display: true,
text: "Chart.js Bar Chart - Stacked"
},
tooltips: {
mode: 'label'
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true,
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.js"></script>
<div style="width: 100%">
<canvas id="canvas"></canvas>
</div>