javascript - ChartJS Javascript - 如何绘制堆积条形直方图但数据集大小未知
问题描述
我想用 ChartJS 绘制一个堆积条形直方图。我看到了很多代码,而且我一般都知道该怎么做。
就我而言,问题如下:
比方说,我有 30 个与标签(或轴)相对应的日期。
然后对于每个日期,我可能有一个或多个显示特定数据的值。
例如:日期 1 --> [1, 2],日期 2 --> [0.5],日期 3 --> [2, 4, 6, 8] 等。
如何知道数据集的大小会有所不同。
到目前为止,我做了这样的事情:
var chartdata = {
labels: [],
datasets: [{
data: []
}, {
data: []
}]
};
var canva_id = "#" + canvaID
var ctx = $(canva_id);
var options = {
maintainAspectRatio: true,
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
scaleLabel: {
display: true,
labelString: 'Date'
},
gridLines: {
display: false
}
}],
yAxes: [{
stacked: true,
ticks: {
beginAtZero: true,
stepSize: 1
},
gridLines: {
display: false
},
scaleLabel: {
display: true,
labelString: 'Nb height'
},
}]
},
legend: {
display: false
},
title: {
display: true,
text: ''
}
}
var chartInstance = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: options
});
[...]
var color = Array("#6ec72e", "#A77A2F", "#BF1515", "#4C4CAD", "#993366", "#401010");
//Dict contain the date as a key and the array of data value as a value
for (const [key, value] of Object.entries(dict)) {
chartInstance.data.labels[key] = value["date"];
chartInstance.update();
var count = 0;
// create a new dataset with empty values
var newDataset = {
data: []
};
chartInstance.data.datasets.push(newDataset);
for (let v = 0; v < value["height"].length; v++) {
chartInstance.data.datasets[key].backgroundColor = color[v];
chartInstance.data.datasets[key].data[v] = value["height"][v];
}
// Finally, make sure you update your chart, to get the result
chartInstance.update();
}
请问有什么帮助吗?
感谢
解决方案
推荐阅读
- flutter - 小部件可以有一个“联合”状态吗?
- reactjs - 在单击跨度时,我们如何使用 useRef() 获取正确的跨度名称
- batch-file - 在批处理脚本中替换特殊符号
- python-3.x - 如何在 Python 中接受带有 Selenium 的 cookie 弹出窗口
- amazon-web-services - AWS S3 访问策略 - 限制文件夹访问
- web3 - 转账ERC20代币失败:web3.exceptions.ContractLogicError:执行恢复:ERC20:从零地址转账
- javascript - Stripe - 退款结账环节
- c++ - 有效地找到系列中的第 n 个数字,其中数字只能被 2,3 和 5 整除
- c - C - 在 Visual Studio 中使用动态结构数组时出现访问错误
- php - php POST 成功从表单同时发送到两个不同的表