我使用 chartjs v3 创建了折线图。我使用自定义工具提示回调函数来显示隐藏数据集/系列的工具提示数据,但我不知道为什么标签颜色方块只显示在一个系列上。有人知道为什么会这样吗?
[https://codepen.io/eidsza/pen/mdWoqOJ][2]
答案 0 :(得分:1)
这是因为您放置的工具提示选项是错误的。并且标签回调会针对每个条目运行,chart.js 会自动将颜色置于其前面,因此您不应返回数组,而应返回该行的单个转换条目,最后一部分不要使用 v3 测试版,使用最新版本。
示例:
var ctx = document.getElementById("chart").getContext("2d");
var chart = new Chart(ctx, {
type: "bar",
data: {
labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
datasets: [{
key: 1,
label: 'series a',
backgroundColor: "rgb(255, 99, 132, 0.5)",
borderColor: "rgb(255, 99, 132)",
borderWidth: 1,
lineTension: 0.3,
data: [10, 7, 9, 5, 8, 3, 4, 2, 1, 1]
},
{
key: 2,
label: 'series b',
backgroundColor: "rgb(30, 105, 122, 0.5)",
borderColor: "rgb(30, 105, 122)",
borderWidth: 1,
lineTension: 0.3,
data: [1, 9, 4, 9, 3, 2, 1, 8, 6, 5]
},
]
},
options: {
interaction: {
intersect: false,
mode: 'index',
},
plugins: {
tooltip: {
callbacks: {
// No callback needed since it seems you want the default behaviour
// label: (item) => {
// // console.log(item.chart)
// // if (item.datasetIndex == item.chart.data.datasets.length - 1) {
// return item.chart.data.datasets.map(ds => ds.label + ': ' + ds.data[item.dataIndex]);
// // }
// // return null;
// }
}
}
}
}
});
.chart {
max-width: 600px;
max-height: 400px;
}
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
<div class="chart">
<canvas id="chart"></canvas>
</div>
<div class="chart">
<canvas id="chart2"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.3.2/dist/chart.min.js"></script>