首页 > 解决方案 > 堆叠的水平图表。如何触发堆叠元素中的单个悬停?

问题描述

我正在尝试为堆叠在水平栏中的数据显示不同的工具提示。代码来自:https ://thewebdev.info/2020/08/18/chart-js%E2%80%8A-%E2%80%8Astacked-bar-chart-and-radial-chart/

var ctx = document.getElementById('myChart').getContext('2d');
var stackedBar = new Chart(ctx, {
type: 'horizontalBar',
data: {
   labels: ['Red', 'Blue', 'Yellow'],
   datasets: [{
   label: '# of Votes',
   data: [12, 19, 3],
   backgroundColor: [
    'rgba(255, 99, 132, 0.2)',
    'rgba(54, 162, 235, 0.2)',
    'rgba(255, 206, 86, 0.2)',
   ],
   borderColor: [
    'rgba(255, 99, 132, 1)',
    'rgba(54, 162, 235, 1)',
    'rgba(255, 206, 86, 1)',
   ],
   borderWidth: 1
  }]
 },
 options: {
   scales: {
     xAxes: [{
       stacked: true
     }],
     yAxes: [{
       stacked: true
     }]
    }
  }
});

在此处输入图像描述 当我们将鼠标悬停在栏上时,无论我们悬停在哪里,它都会立即显示所有堆栈的工具提示数据。但相反,我希望堆栈元素的每个元素都有不同的工具提示。我将非常感谢您的帮助。

标签: graphchart.jsbar-chart

解决方案


您可以为此使用 tooltipmode 点。

例子:

var options = {
  type: 'horizontalBar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        backgroundColor: 'red'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        backgroundColor: 'blue'
      }
    ]
  },
  options: {
    tooltips: {
      mode: 'point'
    },
    scales: {
      yAxes: [{
        stacked: true
      }],
      xAxes: [{
        stacked: true
      }]
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>


推荐阅读