我最近对数据集有相同的要求,并在比例选项中为每个轴使用了回调函数。我将标签的值列表填充到一个数组中,然后使用该点的索引执行查找以重命名刻度标签。
var colours = ["Red", "Blue", "Green", "Yellow"];
var carSizes = ["Small", "Medium", "Large"];
// Small Red = 10
// Small Green = 14
// Medium Yellow = 23
var dataPoints = [{x: 0, y: 0, r: 10}, {x: 2, y: 0, r: 14}, {x: 3, y: 1, r: 23}
var myBubbleChart = new Chart(bubbleCtx, {
type: 'bubble',
data: dataPoints,
options: {
title: {
display: true,
text: "Car Orders"
},
scales: {
yAxes: [{
ticks: {
stepSize: 1,
callback: function (value, index, values) {
if (index < carSizes.length) {
return carSizes[carSizes.length - (1 + index)]; //this is to reverse the ordering
}
}
},
position: 'left'
}],
xAxes: [{
ticks: {
stepSize: 1,
callback: function (value, index, values) {
if (index < colours.length) {
return colours[index];
}
}
},
position: 'bottom'
}]
}
}
});
经过多次尝试和错误,我发现有必要将步长设置为 1,否则图表会因数据出现在网格线之外而出现偏差。
如果您没有动态设置数据并且知道每个轴的最小值和最大值,则可以设置刻度的 min 和 max 属性并将轴类型指定为“类别”。
yAxes: [{
type: 'category',
ticks: {
stepSize: 1,
min: 'Small',
max: 'Large'
},
position: 'left'
}]