sdMarth
sdMarth

Reputation: 561

ChartJS: How to set a data point to be hidden by default?

If I make a pie chart with ChartJS, you are able to toggle some slices on or off. Is it possible to set a single slice to be off by default?

var config = {
  type: 'pie',
  data: {
    datasets: [{
      data: [
        100,
        100,
        200,
        300,
        140
      ],
      backgroundColor: [
        colors.red,
        colors.orange,
        colors.yellow,
        colors.green,
        colors.blue
      ]
    }],
    labels: [
      'Red',
      'Orange',
      'Yellow',
      'Green',
      'Blue'
    ]
  },
  options: {
    // responsive: true,
    maintainAspectRatio: true,
    title: {
      display: true,
      text: 'Colors - Sample Pie Chart'
    }
  }
};

Here is an example:

https://jsfiddle.net/6q1umfxz/

If you click the 'Blue' label under the title, it will hide the blue slice in the pie chart. Is it possible to have only that blue slice hidden by default, without breaking the toggle on / off functionality?

Upvotes: 0

Views: 987

Answers (2)

robinElli
robinElli

Reputation: 31

In V3 of chartjs you can use the API they provide to toggle the visibility of an item.

chart.toggleDataVisibility(2); // toggles the item in all datasets, at index 2
chart.update(); // chart now renders with item hidden

Note: Only doughnut / pie, polar area, and bar use this.

Same answer is posted in this thread: How to hide section in a Chart.js Pie Chart

Upvotes: 0

uminder
uminder

Reputation: 26190

After creating the chart, you can retrieve its metadata through .getDatasetMeta(index), change the hidden attribute of the desired slice and update the chart as follows.

const chart = new Chart(document.getElementById('myChart'), {
  type: 'pie',
  data: {
    labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
    datasets: [{
      data: [100, 100, 200, 300, 140],
      backgroundColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)', 'rgb(54, 162, 235)']
    }]
  },
  options: {
    responsive: true,
    maintainAspectRatio: true,
    title: {
      display: true,
      text: 'Colors - Sample Pie Chart'
    }
  }
});

chart.getDatasetMeta(0).data[4].hidden = true;    
chart.update();
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="150"> </canvas>

Upvotes: 1

Related Questions