Chartjs 没有在工具提示上正确给出 'xLabel'
Chartjs not giving 'xLabel' properly on tooltip
我有一个折线图,其中数据根据 X 轴(时间轴)标签显示为点元素。
// Config chart
const config = {
type: "line",
data: {
labels: ['ene.', 'feb', 'mar.', 'abr.', 'may.', 'jun.', 'jul.', 'ago.', 'sep.', 'oct.', 'nov.', 'dic.'],
datasets // ex --> [{ x: 'jun.', y: 90 }]
},
options: {
tooltips: {
callbacks: {
title: function(context) {
console.log(context); // Returning wrong xLabel
}
}
}
}
}
问题是当它显示 June 的工具提示时,它会将其作为索引 3,因此标题工具提示 (xlabel) 显示为“April”。
我怎样才能在工具提示上获得正确的标签,而不是依赖于索引?
对于 V2,此行为将不再得到修复。但是您可以通过使用为您提供数据的回调中的第二个参数来获得正确的标签:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [{
x: "Red",
y: 5
}, {
x: "Blue",
y: 5
}, {
x: "Purple",
y: 5
}, {
x: "Orange",
y: 5
}],
pointBackgroundColor: 'pink',
borderColor: 'pink',
fill: false
}]
},
options: {
tooltips: {
mode: 'point',
callbacks: {
title: (ctx, data) => (data.datasets[ctx[0].datasetIndex].data[ctx[0].index].x)
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>
我有一个折线图,其中数据根据 X 轴(时间轴)标签显示为点元素。
// Config chart
const config = {
type: "line",
data: {
labels: ['ene.', 'feb', 'mar.', 'abr.', 'may.', 'jun.', 'jul.', 'ago.', 'sep.', 'oct.', 'nov.', 'dic.'],
datasets // ex --> [{ x: 'jun.', y: 90 }]
},
options: {
tooltips: {
callbacks: {
title: function(context) {
console.log(context); // Returning wrong xLabel
}
}
}
}
}
问题是当它显示 June 的工具提示时,它会将其作为索引 3,因此标题工具提示 (xlabel) 显示为“April”。
我怎样才能在工具提示上获得正确的标签,而不是依赖于索引?
对于 V2,此行为将不再得到修复。但是您可以通过使用为您提供数据的回调中的第二个参数来获得正确的标签:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [{
x: "Red",
y: 5
}, {
x: "Blue",
y: 5
}, {
x: "Purple",
y: 5
}, {
x: "Orange",
y: 5
}],
pointBackgroundColor: 'pink',
borderColor: 'pink',
fill: false
}]
},
options: {
tooltips: {
mode: 'point',
callbacks: {
title: (ctx, data) => (data.datasets[ctx[0].datasetIndex].data[ctx[0].index].x)
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>