[Chartjs]-Combining multiple legend elements in chart.js

8๐Ÿ‘

โœ…

I worked out how to do this by adding the following to chart options โ€“
[Assuming your confidence interval are named xxx_lo, xxx, xxx_hi and appear in chartData in that order]

jsfiddle example โ€“ https://jsfiddle.net/5fktnv6a/

labels: {
  filter: function(item, chart) {
    return !item.text.includes('_');
  }
},
onClick: function(e, legendItem) { // need to hide index -1 and index +1
  let index = legendItem.datasetIndex;
  let ci = this.chart;
  let alreadyHidden = (ci.getDatasetMeta(index).hidden === null) ? false : ci.getDatasetMeta(index).hidden;
  let meta_lo = ci.getDatasetMeta(index - 1);
  let meta = ci.getDatasetMeta(index);
  let meta_hi = ci.getDatasetMeta(index + 1);
  if (!alreadyHidden) {
    meta_lo.hidden = true;
    meta.hidden = true;
    meta_hi.hidden = true;
  } else {
    meta_lo.hidden = null;
    meta.hidden = null;
    meta_hi.hidden = null;            
  }

  ci.update();
},

Leave a comment