[Chartjs]-Completely hide the Y-axis on chartjs when data is hidden

1👍

a bit late, but hope it helps someone:

datasets: [
      {
        yAxisID: 'TOGGLE_yaxis1',
        label: 'dataset 1',
        fill: false,
        backgroundColor: 'rgb(255, 99, 132)',
        data: [72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72]
      },
      {
        yAxisID: 'yaxis2',
        label: 'dataset 2',
        fill: false,
        backgroundColor: 'rgb(54, 162, 235)',
        data: [70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70]
      }
    ]

options:
{
    responsive: true,
    legend:{
        display: true,
        onClick: function(event, legendItem) {
           var y_axis_id = MYCHART.data.datasets[legendItem.datasetIndex].yAxisID;
          if(y_axis_id.startsWith('TOGGLE')){
            //find by name yaxis                     
            for(i=0;i<MYCHART.options.scales.yAxes.length;i++){
              if(MYCHART.options.scales.yAxes[i].id==y_axis_id){
                 MYCHART.options.scales.yAxes[i].display = !MYCHART.options.scales.yAxes[i].display;
                 MYCHART.data.datasets[legendItem.datasetIndex].hidden = !MYCHART.data.datasets[legendItem.datasetIndex].hidden; 
                 MYCHART.update();
              }
            }
        }
    },
scales: {
    yAxes: [{
      id: 'TOGGLE_yaxis1'
     },{
      id: 'yaxis2'
     }]}
},

Leave a comment