javascript - 如何在 bar chart.js 的工具提示中显示多个值?
问题描述
我正在使用chart.js。我在下面分享一个例子。当我将鼠标悬停在栏上时,我会收到带有总票数的工具提示。
现在我担心的是,是否可以在工具提示中显示多个值。截至目前,它显示#of Votes 5。
我已经展示了一个更喜欢的Amount 40
。
我尝试了下面的代码,但它不起作用。
data: [[12, 19, 3, 5, 2, 3],[10, 20, 30, 40, 50, 60]],
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
//data: [[12, 19, 3, 5, 2, 3],[10, 20, 30, 40, 50, 60]],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
.innerbox {
width: 600px;
height: 300px;
}
<div class="innerbox">
<canvas id="myChart" width="400" height="300"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
解决方案
您可以使用回调函数afterLabel
显示第二个值,如下所示:
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
tooltips: {
callbacks: {
afterLabel: function(tooltipItem, data) {
var amount = [10, 20, 30, 40, 50, 60];
return "Amount " + amount[tooltipItem['index']];
}
}
}
}
});
.innerbox {
width: 600px;
height: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<div class="innerbox">
<canvas id="myChart" width="400" height="300"></canvas>
</div>
推荐阅读
- three.js - 如何在三个 js 3d .dae 对象中添加按钮
- r - 用 ggplot2 geom_bar() 绘制稍微分开的组内条形图
- itext - IText7 SignatureUtilities GetTranslatedFieldName 返回字符串与字段不匹配(结果缺少“Page1[0]。”)
- r - R:基于另一个变量的因子水平的新变量值
- postgresql - 同时执行创建索引 statmt 并且由于超时错误而断开会话。但我确实在 pg_stat_activity 中看到,它处于运行状态
- python-3.x - 如何仅过滤 jinja2 中的字母
- ios - Apple PDFKit 通知无法正常工作
- python - 当从编辑模式 html 模板发布 django-cms 插件时,不会呈现模型对象。但是切换到编辑模式时内容会重新出现
- excel - 如何使用VBA从excel中的列中删除所有重复项,只留下没有重复的行?
- javascript - 可点击的下拉菜单中的可点击字体真棒图标