我正在try 创建一个基于json数据的条形图,该数据根据过滤器动态变化.
我希望图表显示与该期间相关的类型,如果它存在的话.如果它没有显示任何东西.
我能够得到根据this discussion显示数据的图表,但它只有在数据的所有选项都可用时才起作用,但事实并非如此.
但是,如果句点中缺少某个类型,它会将该类型移回前一段时间段,这是我不想要的.
这里有两个例子
- 两个月,有两种类型,但只有3个值(看起来正确)
[
{
"Period": "2023-12",
"Total": 2238.86,
"Type": "Drinks"
},
{
"Period": "2023-12",
"Total": 4672.35,
"Type": "Food"
},
{
"Period": "2024-01",
"Total": 1166.5,
"Type": "Drinks"
}
]
- 三个月,三种类型,4个值(数据从第二个周期移到第一个周期)
[
{
"Period": "2023-11",
"Total": 2782.13,
"Type": "Other"
},
{
"Period": "2023-12",
"Total": 2238.86,
"Type": "Drinks"
},
{
"Period": "2023-12",
"Total": 4672.35,
"Type": "Food"
},
{
"Period": "2024-01",
"Total": 1166.5,
"Type": "Drinks"
}
]
data from second period shifted to the first period个
我已经找了好几天了,try 了不同的方法,但似乎都不管用.
这是我根据前面提到的主题使用的代码
jQuery.ajax({
url: "../../ajax/barGraph.php?period=<?= $period; ?>",
type: "GET",
dataType: 'json',
success: function(soldeInfo) {
let labels = [...new Set(soldeInfo.map((x) => x.Period))];
let datasets = soldeInfo.reduce(function (acc, cur) {
let Type = acc.find((x) => x.label == cur.Type);
if (Type == null) {
let color = '';
switch (cur.Type) {
case 'Food':
color = 'red';
break;
case 'Drinks':
color = 'green';
break;
default:
color ='gray';
}
Type = {
label: cur.Type,
data: [cur.Total],
backgroundColor: color,
borderColor: color,
borderWidth: 1,
};
acc.push(Type);
} else {
Type.data.push(cur.Total);
}
return acc;
}, []);
var soldeInfo = {
type: 'bar',
data: {
labels: labels,
datasets: datasets,
},
};
const soldeChart = document.getElementById('chartSolde');
new Chart(soldeChart, soldeInfo);
}
});
非常感谢:)