Chartjs-Hide/show spefic data in ChartJS

0👍

This can be done with the following onclick event handler. If a click occurs in the region below the chart, the function first toggles the visibility of the data that matches the x index. Then, it computes the new y.max and finally invokes chart.update().

document.getElementById('canvas').onclick = evt => {
  if (chart.scales['y'].getValueForPixel(evt.clientY) > 0) {
    return; 
  }
  const indexX = chart.scales['x'].getValueForPixel(evt.clientX);
  chart.toggleDataVisibility(indexX);
  chart.options.y.max = chart.data.datasets
    .map(ds => ds.data.map((v, i) => chart.getDataVisibility(i) ? v : 0))
    .flatMap(data => data)
    .reduce((max, v) => max > v ? max : v);
  chart.update();
};

For further information about getValueForPixel and toggleDataVisibility, please consult the Chart.js documentation.

Please take a look at below runnable code and see how it works. Click on on the desired x label to have the chart redrawn.

const chart = new Chart('canvas', {
  type: 'bar',
  data: {
    labels: ['A', 'B', 'C', 'D', 'E', 'F'],
    datasets: [{
        label: 'Dataset 1',
        data: [3, 9, 7, 150, 9, 2],
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        borderColor: 'rgb(255, 99, 132)',
        fill: false
      },
      {
        label: 'Dataset 2',
        data: [4, 8, 12, 145, 6, 4],
        backgroundColor: 'rgba(132, 99, 255, 0.2)',
        borderColor: 'rgb(132, 99, 255)',
        fill: false
      }
    ]
  },
  options: {
    y: {}
  }
});

const canvas = document.getElementById('canvas');
canvas.onclick = evt => {
  if (chart.scales['y'].getValueForPixel(evt.clientY) > 0) {
    return; 
  }
  const indexX = chart.scales['x'].getValueForPixel(evt.clientX);
  chart.toggleDataVisibility(indexX);
  chart.options.y.max = chart.data.datasets
    .map(ds => ds.data.map((v, i) => chart.getDataVisibility(i) ? v : 0))
    .flatMap(data => data)
    .reduce((max, v) => max > v ? max : v);
  chart.update();
};

canvas.onmousemove = evt => {
  const v = chart.scales['y'].getValueForPixel(evt.clientY);
  const indexX = chart.scales['x'].getValueForPixel(evt.clientX)
  canvas.style.cursor = v < 0 && indexX >= 0 ? 'pointer' : 'default';
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="canvas" height="80"></canvas>

Leave a comment