score:0

Accepted answer

you can make use of the legend onclick handler like so:

const defaultlegendclickhandler = chart.defaults.plugins.legend.onclick;
const piedoughnutlegendclickhandler = chart.controllers.doughnut.overrides.plugins.legend.onclick;

const options = {
  type: 'line',
  data: {
    labels: ["red", "blue", "yellow", "green", "purple", "orange"],
    datasets: [{
        label: 'strength',
        data: [12, 19, 3, 5, 2, 3],
        bordercolor: 'pink'
      },
      {
        label: 'avg data, %',
        data: [7, 11, 5, 8, 3, 7],
        bordercolor: 'orange'
      }
    ]
  },
  options: {
    plugins: {
      legend: {
        onclick: (evt, legenditem, legend) => {
          const type = legend.chart.config.type;

          if (type === 'pie' || type === 'doughnut') {
            piedoughnutlegendclickhandler(evt, legenditem, legend)
          } else {
            defaultlegendclickhandler(evt, legenditem, legend);
          }

          if (legenditem.text !== 'strength') {
            return;
          }

          legend.chart.options.plugins.annotation.annotations.line1.display = !legend.chart.getdatasetmeta(0).hidden;
          legend.chart.update();
        }
      },
      annotation: {
        annotations: {
          line1: {
            type: 'line',
            ymin: 4,
            ymax: 6,
            bordercolor: 'rgba(234,6,6,0.7)',
            borderwidth: 1,
            borderdash: [2, 2],
            display: true
          }
        }
      }
    }
  }
}

const 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/3.5.1/chart.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/1.0.2/chartjs-plugin-annotation.js"></script>
</body>


Related Query

More Query from same tag