[Chartjs]-Chart.js Multiple charts with one common legend

7๐Ÿ‘

โœ…

You can create a common legend and through generateLegend api, if both the datasets are similar.

First disable the default legends though the options

legend: {
        display: false
      }

Then use generateLegend() api to get the data labels and set it to a common element.

<ul class="legend">

</ul>

Then add event listeners to the generated elements and target all the charts

document.querySelector('.legend').innerHTML = myChartA.generateLegend();

var legendItems = document.querySelector('.legend').getElementsByTagName('li');
for (var i = 0; i < legendItems.length; i++) {
  legendItems[i].addEventListener("click", legendClickCallback.bind(this,i), false);
}

function legendClickCallback(legendItemIndex){
  document.querySelectorAll('.myChart').forEach((chartItem,index)=>{
    var chart = Chart.instances[index];
    var dataItem = chart.data.datasets[legendItemIndex]    
    if(dataItem.hidden == true || dataItem.hidden == null){
      dataItem.hidden = false;
    } else {
      dataItem.hidden = true;
    }
    chart.update();
  })  
}

A sample pen is present here
https://codepen.io/srajagop/pen/yLBJOOo

Note I am using chartjs 2.8

1๐Ÿ‘

If anyone using React version of Chartjs particularly react-chartjs-2, I have done it using React Hooks with react-chartjs-2, see the sandbox demo

Leave a comment