gpt4 book ai didi

chart.js - 在 Chart.js 中创建分组和堆叠图表

转载 作者:行者123 更新时间:2023-12-03 20:17:28 25 4
gpt4 key购买 nike

我想知道是否可以在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>

最佳答案

您可以通过设置 stacked 来堆叠条形图。在 x 轴和 y 轴上选择为 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>

关于chart.js - 在 Chart.js 中创建分组和堆叠图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47771823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com