我只是一个试图创建每秒钟动态更新的条形图的人。我发现JS是个不错的选择(我不知道如何使用Excel做到这一点)。
在对JS进行了一些研究并最终使其动态化并按从最高到最低的顺序进行排序之后,我发现了一些问题,希望您能为我提供帮助:
const CHART = document.getElementById("chart");
Chart.defaults.global.animation.duration = 1000;
Chart.plugins.register({
beforeUpdate: function(chart) {
if (chart.options.sort) {
let dataArray = chart.data.datasets[0].data.slice();
let dataIndexes = dataArray.map((d, i) => i);
dataIndexes.sort((a, b) => {
return dataArray[a] - dataArray[b];
});
// sort data array as well
dataArray.sort((a, b) => b - a);
// At this point dataIndexes is sorted by value of the data, so we know how the indexes map to each other
let meta = chart.getDatasetMeta(0);
let newMeta = [];
let labels = chart.data.labels;
let newLabels = [];
meta.data.forEach((a, i) => {
newMeta[dataIndexes[i]] = a;
newLabels[dataIndexes[i]] = chart.data.labels[i];
});
meta.data = newMeta;
chart.data.datasets[0].data = dataArray;
chart.data.labels = newLabels;
}
}
});
setInterval(function() {
let barChart = new Chart(CHART, {
type: 'horizontalBar',
data: {
labels: ['Chicken', 'Tuna', 'Cow', 'Pig', 'Dog', 'Mermaid'],
datasets: [{
label: "Animals (and Mermaid)",
//How to stick this background colors to each label
backgroundColor: [
"#467261",
"#556e69",
"#555341",
"#4e6577",
"#537061",
"#44656e"
],
data: [Math.random()*1000, Math.random()*1000, Math.random()*1000, Math.random()*1000, Math.random()*1000, Math.random()*1000]
}]
},
options: {
scales: {
xAxes: [{
ticks: {
beginAtZero: true
}
}],
yAxes: [{
barThickness: 30
}]
}
}
});
barChart.options.sort = true;
barChart.update();
},3000);
预先感谢
答案 0 :(得分:0)
您可以在单个数组中创建数据,并按每个间隔的随机值对数据进行排序,然后将其全部排序。
var adata = [
["Chicken", "red", Math.random()*1000],
["Tuna", "#556e69", Math.random()*1000],
["Cow", "#555341", Math.random()*1000],
["Pig", "#4e6577", Math.random()*1000],
["Dog", "#537061", Math.random()*1000],
["Mermaid", "#44656e", Math.random()*1000],
];
adata.sort(function(a, b) {return b[2] - a[2];});
然后,您必须删除在beforeUpdate中完成的所有排序功能。