我正在尝试构建一个chart.js散点图,当用户将鼠标悬停在散点上时,工具提示会显示特定到该点的标签。
因此每个数据点都有它的x和y值,以及它的标签。
到目前为止我已经
了
var ctx = document.getElementById('myChart').getContext('2d');
var scatterChart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
labels: ["Label 1","Label 2","Label 3"],
data: [{
x: -10,
y: 0,
}, {
x: 0,
y: 10
}, {
x: 10,
y: 5
}]
}]
},
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || 'Other';
var label = data.labels[tooltipItem.index];
return datasetLabel + ': ' + label;
}
}
}
}
});
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
</head>
<canvas id="myChart" style = "height:1000px"></canvas>
当我将鼠标悬停在每个点上时,我希望看到“标签1”,“标签2”或“标签3”。
非常感谢
答案 0 :(得分:14)
您可以使用以下工具提示标签回调函数来实现此目的...
//varTypes.h
struct TypeOne {int a; int b;};
struct TypeTwo {int c; int d;};
//varTypes.c
include "varTypes.h"
varTypes::TypeOne x {1, 1};
varTypes::TypeTwo y {1, 2};
varTypes::TypeTwo z {2, 4};
ᴡᴏʀᴋɪɴɢᴡᴏʀᴋɪɴɢxᴀᴍᴘʟᴇ
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.labels[tooltipItem.index];
return label + ': (' + tooltipItem.xLabel + ', ' + tooltipItem.yLabel + ')';
}
}
}
var ctx = document.getElementById('myChart').getContext('2d');
var scatterChart = new Chart(ctx, {
type: 'scatter',
data: {
labels: ["Label 1", "Label 2", "Label 3"],
datasets: [{
label: 'Legend',
data: [{
x: -10,
y: 0,
}, {
x: 0,
y: 10
}, {
x: 10,
y: 5
}]
}]
},
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.labels[tooltipItem.index];
return label + ': (' + tooltipItem.xLabel + ', ' + tooltipItem.yLabel + ')';
}
}
}
}
});
答案 1 :(得分:2)
从 Chart.js 版本 3 开始,回调的处理方式略有不同。这是 3.2.0 的工作示例。相关文档:https://www.chartjs.org/docs/latest/configuration/tooltip.html#label-callback
ctx = document.getElementById("myChart").getContext("2d");
let data = {
datasets: [{
label: "Legend",
labels: ["Label 1", "Label 2", "Label 3"],
data: [{
x: -10,
y: 0,
}, {
x: 0,
y: 10
}, {
x: 10,
y: 5
}],
backgroundColor: "rgb(255, 99, 132)"
}]
}
let options = {
plugins: {
tooltip: {
callbacks: {
label: function(ctx) {
// console.log(ctx);
let label = ctx.dataset.labels[ctx.dataIndex];
label += " (" + ctx.parsed.x + ", " + ctx.parsed.y + ")";
return label;
}
}
}
}
}
scatterChart = new Chart(ctx, {
type: "scatter",
data: data,
options: options
});
<canvas id="myChart" height="500"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.2.0/chart.min.js"></script>
答案 2 :(得分:1)
对于多个标签,需要将GRUNT的答案修改为使用 tooltipItem.datasetIndex 而不是tooltipItem.index:
StreamWriter