Chartjs-How to noshown the scale while all datasets is hidden (chartjs)?

1đź‘Ť

Without fully knowing exactly what you are wanting to show/hide, I put together an example that hides the x/y axes when all series are turned off. To do this I followed the instructions in their documentation about how write an onClick handler for the legend.

Here is the relevant code for that handler:

{
  ...
  options: {
    scales: {
        yAxes: [{
        display: true, // <-- Added to make sure property was in options to read
        ...
      }],
      xAxes: [{
        display: true // <-- Added to make sure property was in options to read
      }]
    },
    legend: {
      onClick: function (e, legendItem) {
        const index = legendItem.datasetIndex;
        const ci = this.chart;
        var meta = ci.getDatasetMeta(index);

        meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;

        /* Start: Custom code to handle the showing/hiding */
        const allHidden = ci.data.datasets.every((dataSet, index) => ci.getDatasetMeta(index).hidden);

        ci.options.scales.yAxes[0].display = !allHidden;
        ci.options.scales.xAxes[0].display = !allHidden;
        /* End: Custom code to handle the showing/hiding */

        // We hid a dataset ... rerender the chart
        ci.update();
      }
    }
  }
});

1đź‘Ť

I follow Daniel’s proposal and rewrite the custom onClick function. Now it’s working exactly as I expected.

//start
const allHidden = ci.data.datasets.every((dataSet, index) => ci.getDatasetMeta(index).hidden)

const rightAxisDataSetsAllHidden = ci.data.datasets.every((dataSet, i) => {
if (ci.getDatasetMeta(i).yAxisID === "rightAxis") {
  if (ci.getDatasetMeta(i).hidden === null) {
    return false}
  else {
    return true
  }
}
else {
  return true
}})

const leftAxisDataSetsAllHidden = ci.data.datasets.every((dataSet, i) => {
if (ci.getDatasetMeta(i).yAxisID === "leftAxis") {
  if (ci.getDatasetMeta(i).hidden === null) {
    return false
  }
  else {
    return true
  }
}
else {
  return true
}})

if (ci.options.scales.yAxes.length != 1) {
  ci.options.scales.yAxes[0].display = !leftAxisDataSetsAllHidden
  ci.options.scales.yAxes[1].display = !rightAxisDataSetsAllHidden
}
else {
  ci.options.scales.yAxes[0].display = !leftAxisDataSetsAllHidden;
}
ci.options.scales.xAxes[0].display = !allHidden;
//end

Leave a comment