考虑到chartjs网站[底部(http://tobiasahlin.com/blog/chartjs-charts-to-get-you-started/#10-bubble-chart)的以下代码,必须分别分配每个数据点,这也占用了大量空间。假设我在列表中同时包含了所有x,y和r。这是一个开放式问题,而不是寻找受限制的解决方案。我将如何实现下面的伪代码?
labelList=['China','Denmark','Germany','Japan']
xlist= [21269017,258702, 3979083,4931877]
ylist = [5.245,7.526,6.994,5.921]
rlist = [15,10,15,15]
datasets: [
{
label: labelList,
data: [{
x: xlist,
y: ylist,
r: rlist
}]
}
new Chart(document.getElementById("bubble-chart"), {
type: 'bubble',
data: {
datasets: [
{
label: ["China"],
data: [{
x: 21269017,
y: 5.245,
r: 15
}]
}, {
label: ["Denmark"],
data: [{
x: 258702,
y: 7.526,
r: 10
}]
}, {
label: ["Germany"],
data: [{
x: 3979083,
y: 6.994,
r: 15
}]
}, {
label: ["Japan"],
data: [{
x: 4931877,
y: 5.921,
r: 15
}]
}
]
},
options: {
title: {
display: true,
text: 'Predicted world population (millions) in 2050'
}, scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: "Happiness"
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: "GDP (PPP)"
}
}]
}
}
});
答案 0 :(得分:1)
首先,您需要检查xList
,yList
,rList
和labelList
的长度是否相同,否则显然我们不能这样做。
之后,我们可以使用如下简单代码生成必要的数据结构:
labelList = ['China', 'Denmark', 'Germany', 'Japan']
xList = [21269017, 258702, 3979083, 4931877]
yList = [5.245, 7.526, 6.994, 5.921]
rList = [15, 10, 15, 15]
if ([labelList.length, xList.length, yList.length, rList.length].every((v, i, arr) => v == arr[0])) {
datasets = [...Array(labelList.length).keys()].map(i => ({
label: labelList[i],
data: [{
x: xList[i],
y: yList[i],
r: rList[i]
}]
}))
console.log(datasets);
}