首页 > 解决方案 > 如何在 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>

在此处输入图像描述

标签: javascriptjquerychart.jstooltipbar-chart

解决方案


您可以使用回调函数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>


推荐阅读