gpt4 book ai didi

javascript - Chart.js 根据时间单位求和 y 值

转载 作者:行者123 更新时间:2023-12-05 05:45:33 26 4
gpt4 key购买 nike

Chart.js 的新手,我想知道是否有一种内置方法可以根据时间单位对 y 值求和。
在文档中进行大量搜索后在这里询问。

目前,3 月的条形图显示 20,6 月的条形图显示 10。
我想 3 月有 25 个,6 月有 15 个,所以要对同一个月的 y 求和。

const ctx = document.getElementById("tests-chart")
const testsChart = new Chart(ctx, {
type: "bar",
data: {
datasets: [
{
label: 'Dataset 1',
data: [
{ x: "24/03/2022", y: 20 },
{ x: "25/03/2022", y: 5 },
{ x: "24/06/2022", y: 10 },
{ x: "25/06/2022", y: 5 },
],
backgroundColor: 'rgb(255, 99, 132)',
},
],
},
options: {
scales: {
x: {
type: "time",
time: {
parser: "dd/MM/yyyy",
unit: "month",
// Luxon format string
tooltipFormat: "MM",
round: 'month'
},
},
},
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@2.3.1/build/global/luxon.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@1.1.0/dist/chartjs-adapter-luxon.min.js"></script>
<div>
<canvas id="tests-chart"></canvas>
</div>

最佳答案

您可以如下所述操作您的数据集并实现您的预​​期输出。

const ctx = document.getElementById("tests-chart");
const data =[
{ x: "24/03/2022", y: 20 },
{ x: "25/03/2022", y: 5 },
{ x: "24/06/2022", y: 10 },
{ x: "25/06/2022", y: 5 }
];

let updatedData =[];
let tempDateCollection =[];

data.map((yData , index)=> {

const formatedDate = moment(yData.x, "DD/MM/YYYY").format('MMM/YYYY');

if(tempDateCollection.includes(formatedDate)){
const index = tempDateCollection.indexOf(formatedDate);
const element = updatedData[index];
updatedData[index] = {...element, y: element.y + yData.y}
} else{
tempDateCollection.push(formatedDate);
updatedData.push(yData);
}

})

const testsChart = new Chart(ctx, {
type: "bar",
data: {
datasets: [
{
label: 'Dataset 1',
data:updatedData,
backgroundColor: 'rgb(255, 99, 132)',
},
],
},
options: {
scales: {
x: {
type: "time",
time: {
parser: "dd/MM/yyyy",
unit: "month",
// Luxon format string
tooltipFormat: "MM",
round: 'month'
},
},
},
},
})
<script type = "text/JavaScript" src = " https://MomentJS.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@2.3.1/build/global/luxon.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@1.1.0/dist/chartjs-adapter-luxon.min.js"></script>

<div>
<canvas id="tests-chart"></canvas>
</div>

关于javascript - Chart.js 根据时间单位求和 y 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71332540/

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