Chartjs-Chart.js – Hide line using label string after load

2πŸ‘

βœ…

If you want to hide a dataset after the chart has been initialized (and rendered), then you still use the dataset hidden: true property. You simply just have to access the dataset from your chart instance and set the property to true.

Here is an example where a dataset matching a label is hidden 5 seconds after the page loads.

// the dataset label we want to hide after chart is initialized
var hiddenLabel = 'My Second Dataset';
var timerDuration = 5;

// hide a dataset after X seconds
setTimeout(function() {
  var indexToHide = -1;  

  // find which dataset matches the label we want to hide
  myLine.config.data.datasets.forEach(function(e, i) {
    if (e.label === hiddenLabel) {
      indexToHide = i;
    }
  });

  // get the dataset meta object so we can hide it
  var meta = myLine.getDatasetMeta(indexToHide);

  // hide the dataset and re-render the chart
  meta.hidden = true;
  myLine.update();
}, timerDuration * 1000);

As you can see, you can just iterate over the datasets to find the index of the dataset with the matching label, then you simply set the hidden property to true and update the chart.

Here is a codepen that demonstrates a full working example.

With that said, it’s not clear why you would want to do this after the chart is hidden. If you already know which dataset you want hidden at page load time, then you could just assemble your data and options chart config dynamically and set the hidden flag to true programmatically. Here is an example.

// the dataset label we want to hide
var hiddenLabel = 'My Second Dataset';

// build our data and options config (if needed you could build the datasets dynamically from dynamic data (this example is static)
var config = {
  type: 'line',
  data: {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
      label: "My First Dataset",
      backgroundColor: chartColors.red,
      borderColor: chartColors.red,
      data: [5, 10, 25, 15, 10, 20, 30],
      fill: false,
    }, {
      label: "My Second Dataset",
      fill: false,
      backgroundColor: chartColors.blue,
      borderColor: chartColors.blue,
      data: [5, 0, 12, 5, 25, 35, 15],
    }]
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: 'Chart.js Hide Dataset Matching "My Seconds Dataset" After 3 Seconds'
    },
    tooltips: {
      mode: 'index',
      intersect: false,
    },
    hover: {
      mode: 'nearest',
      intersect: true
    },
    scales: {
      xAxes: [{
        display: true,
        scaleLabel: {
          display: true,
          labelString: 'Month'
        }
      }],
    }
  }
};

// iterate over our datasets to find the one we want to hide
config.data.datasets.forEach(function(e) {
  if (e.label === hiddenLabel) {
    e.hidden = true;
  }
});

// instantiate the chart
var myLine = new Chart($('#canvas'), config);

Leave a comment