要同时为 X 轴和 Y 轴使用类别比例,您必须使用值数组的传统数据格式。根据chart.js api docs...
可以通过将 X 轴更改为线性轴来创建散点线图。要使用散点图,数据必须作为包含 X 和 Y 属性的对象传递
这意味着您只能在至少 X 轴是线性刻度时使用数据格式 {x: ' ', y: ' '}(但我敢打赌,它只有在 X 和 Y 轴都是线性的情况下才有效)。
由于您仅限于为数据使用一组值,因此您必须使用至少 2 个数据集才能在 X 轴上绘制多个值(就像您尝试做的那样)。
这是一个图表配置,可以提供您正在寻找的内容。
var ctx = document.getElementById("canvas").getContext("2d");
var myLine = new Chart(ctx, {
type: 'line',
data: {
xLabels: ["January", "February", "March", "April", "May", "June", "July"],
yLabels: ['Request Added', 'Request Viewed', 'Request Accepted', 'Request Solved', 'Solving Confirmed'],
datasets: [{
label: "My First dataset",
data: ['Request Added', 'Request Viewed', 'Request Added'],
fill: false,
showLine: false,
borderColor: chartColors.red,
backgroundColor: chartColors.red
}, {
label: "My First dataset",
data: [null, 'Request Accepted', 'Request Accepted'],
fill: false,
showLine: false,
borderColor: chartColors.red,
backgroundColor: chartColors.red
}]
},
options: {
responsive: true,
title:{
display: true,
text: 'Chart.js - Non Numeric X and Y Axis'
},
legend: {
display: false
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
type: 'category',
position: 'left',
display: true,
scaleLabel: {
display: true,
labelString: 'Request State'
},
ticks: {
reverse: true
},
}]
}
}
});
你可以从这个codepen看到它的样子。
如果您出于某种原因与使用 {x: ' ', y: ' '} 数据格式相关,那么您必须将两个刻度都更改为线性,将您的数据映射到数值,然后使用 ticks.callback 属性将您的数字刻度映射回到字符串值。
这是一个演示此方法的示例。
var xMap = ["January", "February", "March", "April", "May", "June", "July"];
var yMap = ['Request Added', 'Request Viewed', 'Request Accepted', 'Request Solved', 'Solving Confirmed'];
var mapDataPoint = function(xValue, yValue) {
return {
x: xMap.indexOf(xValue),
y: yMap.indexOf(yValue)
};
};
var ctx2 = document.getElementById("canvas2").getContext("2d");
var myLine2 = new Chart(ctx2, {
type: 'line',
data: {
datasets: [{
label: "My First dataset",
data: [
mapDataPoint("January", "Request Added"),
mapDataPoint("February", "Request Viewed"),
mapDataPoint("February", "Request Accepted"),
mapDataPoint("March", "Request Added"),
mapDataPoint("March", "Request Accepted"),
],
fill: false,
showLine: false,
borderColor: chartColors.red,
backgroundColor: chartColors.red
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js - Scatter Chart Mapping X and Y to Non Numeric'
},
legend: {
display: false
},
scales: {
xAxes: [{
type: 'linear',
position: 'bottom',
scaleLabel: {
display: true,
labelString: 'Month'
},
ticks: {
min: 0,
max: xMap.length - 1,
callback: function(value) {
return xMap[value];
},
},
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Request State'
},
ticks: {
reverse: true,
min: 0,
max: yMap.length - 1,
callback: function(value) {
return yMap[value];
},
},
}]
}
}
});
您可以在同一codepen 看到这一点。