我想知道是否可以在Chart js中创建分组和堆积的图表。
我有两组数据,每组都有一个正(收入)和负(税)成分,因此希望“堆积”数据。这些在一起。我还提出了两个数据案例 - 一个基础和敏感性案例,因此我们希望对这些数据进行分组。每个案例彼此相邻。
如果数据沿x轴堆叠,则条形重叠,如果数据未堆叠,则正(收入)条形图从相应的负(税)条偏移 - 此切换可在下面的代码中看到'堆积'选项。
我想将收入和税收组成部分叠加在一起,并将每个案例集中在一起,以便整齐地显示图表。这可能吗?任何帮助或见解将不胜感激。
我的图表代码如下:
new Chart(document.getElementById("MyChart"), {
type: 'bar',
data: {
labels: [2017, 2018, 2019, 2020, 2021, 2022, 2023],
datasets: [{
label: "Income - Base",
type: "bar",
backgroundColor: "#eece01",
data: [30, 31, 32, 33, 34, 35, 36],
}, {
label: "Income - Sensitivity",
type: "bar",
backgroundColor: "#f8981f",
data: [20, 21, 22, 23, 24, 25, 26],
}, {
label: "Tax - Base",
type: "bar",
backgroundColor: "#87d84d",
data: [-15, -16, -17, -18, -19, -20, -21],
}, {
label: "Tax - Sensitivity",
type: "bar",
backgroundColor: "#00b300",
backgroundColorHover: "#3e95cd",
data: [-10, -11, -12, -13, -14, -15, -16]
}
]
},
options: {
scales: {
xAxes: [{
//stacked: true,
stacked: false,
ticks: {
beginAtZero:true,
maxRotation: 0,
minRotation: 0
}
}],
yAxes: [{
stacked: false,
}]
},
}
});

<canvas id="MyChart" width="400" height="200"></canvas>
&#13;
答案 0 :(得分:3)
您可以通过在x轴和y轴上将stacked
选项设置为true来堆叠条形图,并定义数据集的stack
组属性。
以下是包含建议更改的代码段:
new Chart(document.getElementById("MyChart"), {
type: 'bar',
data: {
labels: [2017, 2018, 2019, 2020, 2021, 2022, 2023],
datasets: [{
label: "Income - Base",
type: "bar",
stack: "Base",
backgroundColor: "#eece01",
data: [30, 31, 32, 33, 34, 35, 36],
}, {
label: "Tax - Base",
type: "bar",
stack: "Base",
backgroundColor: "#87d84d",
data: [-15, -16, -17, -18, -19, -20, -21],
}, {
label: "Income - Sensitivity",
type: "bar",
stack: "Sensitivity",
backgroundColor: "#f8981f",
data: [20, 21, 22, 23, 24, 25, 26],
}, {
label: "Tax - Sensitivity",
type: "bar",
stack: "Sensitivity",
backgroundColor: "#00b300",
backgroundColorHover: "#3e95cd",
data: [-10, -11, -12, -13, -14, -15, -16]
}]
},
options: {
scales: {
xAxes: [{
//stacked: true,
stacked: true,
ticks: {
beginAtZero: true,
maxRotation: 0,
minRotation: 0
}
}],
yAxes: [{
stacked: true,
}]
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<canvas id="MyChart" width="400" height="200"></canvas>