1
votes

I've got a horizontal stacked bar chart rendered in Chart.js, and the legend corresponds to the different classes. Here's a bit of it (working on a dummy dataset, disregard the nonsense names): enter image description here

The labels on the left are users, the labels in the legend (which correspond to the classes in the bar chart, i.e. the different datasets) are mailing lists. The chart, basically, shows how many users are members of specific mailing lists; the length of the bar is how many mailing lists a given user is a member of.

What I'd like to do is set it up so hovering over an entry in the legend will highlight (ideally with a border or something) the portions of the bar chart corresponding to that dataset. So if I hovered over the first dataset entry, the blue block at the left end of all those bars (except "anionic") would get a highlight.

Using the onHover and onLeave events for the legend, I'm successfully console.log'ing the currently-hovered dataset index. But I can't figure out how to make the bar elements belonging to that dataset highlight.

1

1 Answers

0
votes

With the new upcomming release of version 3 you can do this with the setActive elements.

Documentation: https://www.chartjs.org/docs/master/developers/api/#setactiveelementsactiveelements

var options = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1,
        hoverBackgroundColor: 'green',
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1,
        hoverBackgroundColor: 'red',
      }
    ]
  },
  options: {
    scales: {}
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
chart.setActiveElements([{
  datasetIndex: 0,
  index: 1,
}, {
  datasetIndex: 1,
  index: 1,
}]);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0-beta.10/chart.js" integrity="sha512-7igYTuENB1pHNsZ/SyzMYrcJAmRCk084yVOsxNNCQAdX1wSYvCeBOgSOMC6wUdKMO76kCJNOpW4jY3UW5CoBnA==" crossorigin="anonymous"></script>
</body>