score:22

Accepted answer

if you need to show/hide charts selecting/unselecting all labels here is an example:

var barchartdata = {
  labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32],
  datasets: [{
    label: 'one',
    backgroundcolor: 'rgba(206, 0, 23, 1)',
    data: [0, 1, 3, 0, 2, 0, 0, 2, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 2, 1, 0, 1, 2, 1, 1, 0, 0, 0, 2, 2, 0, 3]
  }, {
    label: 'two',
    backgroundcolor: 'rgba(206, 0, 23, 0.75)',
    data: [0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1]
  }, {
    label: 'three',
    backgroundcolor: 'rgba(206, 0, 23, 0.5)',
    data: [0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 2, 0, 0, 0, 1, 0, 0, 0, 0, 1]
  }]

};
var ctx = document.getelementbyid('canvas').getcontext('2d');
var chartinstance = new chart(ctx, {
  type: 'bar',
  data: barchartdata,
  options: {
    title: {
      display: false,
    },
    responsive: true,
    scales: {
      xaxes: [{
        stacked: true,
      }],
      yaxes: [{
        stacked: true
      }]
    }
  }
});

$("#toggle").click(function() {
	 chartinstance.data.datasets.foreach(function(ds) {
    ds.hidden = !ds.hidden;
  });
  chartinstance.update();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/2.7.2/chart.bundle.min.js"></script>
<button id="toggle">show/hide all</button>
<canvas id="canvas" height="500" width="800"></canvas>

jsfiddle: https://jsfiddle.net/beaver71/00q06vjp/

credits: see https://github.com/chartjs/chart.js/issues/3009


update: for pie chart use "meta", see: https://jsfiddle.net/beaver71/u0y0919b/

score:0

the correct answer result in :

chart.data.datasets.foreach((obj, index) => {
   let meta = this.eval_chart.getdatasetmeta(index);
   meta.hidden = !meta.hidden || null;
});
chart.update();

as wrote in the documentation : https://www.chartjs.org/docs/latest/configuration/legend.html#custom-on-click-actions

score:1

v3 answer

you can use a custom generatelabels function together with a custom onclick to get it as an extra legenditem 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: '# of votes',
        data: [12, 19, 3, 5, 2, 3],
        bordercolor: 'pink'
      },
      {
        label: '# of points',
        data: [7, 11, 5, 8, 3, 7],
        bordercolor: 'orange'
      }
    ]
  },
  options: {
    plugins: {
      legend: {
        onclick: (evt, legenditem, legend) => {
          const type = legend.chart.config.type;
          let alllegenditemsstate = [];

          if (legenditem.text === 'hide all datasets' || legenditem.text === 'show all datasets') {
            if (typeof legend.hideall === 'undefined') {
              legend.hideall = false;
            }

            legend.chart.data.datasets.foreach((dataset, i) => {
              legend.chart.setdatasetvisibility(i, legend.hideall)
            });

            legend.hideall = !legend.hideall;
            legend.chart.update();

            return;
          }

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

          alllegenditemsstate = legend.chart.data.datasets.map((e, i) => (legend.chart.getdatasetmeta(i).hidden));

          if (alllegenditemsstate.every(el => !el)) {
            legend.hideall = false;
            legend.chart.update();
          } else if (alllegenditemsstate.every(el => el)) {
            legend.hideall = true;
            legend.chart.update();
          }
        },
        labels: {
          generatelabels: (chart) => {
            const datasets = chart.data.datasets;
            const {
              labels: {
                usepointstyle,
                pointstyle,
                textalign,
                color
              }
            } = chart.legend.options;

            const legenditems = chart._getsorteddatasetmetas().map((meta) => {
              const style = meta.controller.getstyle(usepointstyle ? 0 : undefined);

              return {
                text: datasets[meta.index].label,
                fillstyle: style.backgroundcolor,
                fontcolor: color,
                hidden: !meta.visible,
                linecap: style.bordercapstyle,
                linedash: style.borderdash,
                linedashoffset: style.borderdashoffset,
                linejoin: style.borderjoinstyle,
                strokestyle: style.bordercolor,
                pointstyle: pointstyle || style.pointstyle,
                rotation: style.rotation,
                textalign: textalign || style.textalign,
                datasetindex: meta.index
              };
            });

            legenditems.push({
              text: (!chart.legend.hideall || typeof chart.legend.hideall === 'undefined') ? 'hide all datasets' : 'show all datasets',
              fontcolor: color,
              fillstyle: 'turquoise', // box color
              strokestyle: 'turquoise', // linecollor around box
            });

            return legenditems;
          }
        }
      }
    }
  }
}

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.6.0/chart.js"></script>
</body>

score:2

for chartjs 2.9.3, this works as requested by david in the comments:

const chart = ...
chart.data.datasets.foreach(dataset => {
  object.keys(dataset._meta).foreach(key => {
    const current = !dataset._meta[key].hidden
    dataset._meta[key].hidden = current || null
  })
})
chart.update()

toggles all with a button, while playing nicely with the individual toggling in the chart legend.


Related Query

More Query from same tag