0
votes

I am trying to create a pie chart in JavaScript. I would like this chart to display in the legend only the labels that are non zero.

Does anyone have any ideas how this can be done?

Here is the code I have so far. Currently the legend of the pie chart shows all possible 12 Labels, even though 8 of these have zero value. "Data" will eventually be filled from a database and therefore it is important that this is an automated process.

var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
  type: 'pie',
  data: {
    labels: ["Astronomica", "Deuteronic", "Floral", "Galactic","Celestrial","Heliosphere","Jupiter","Interstella","Koronis","Eclipse,"Borealis","Lunatic"],
    datasets: [{
      data: [12.21, 15.58, 11.25, 8.32],
      backgroundColor: ['#007bff', '#dc3545', '#ffc107', '#28a745'],
    }],
  },
});
2

2 Answers

1
votes

You can manage data before use they.

var ctx = document.getElementById("myPieChart");
var input_lables = ["Astronomica" , "Deuteronic", "Floral", "Galactic", "Celestrial", "Heliosphere", "Jupiter", "Interstella","Koronis", "Eclipse", "Borealis", "Lunatic"];
var input_values = [12.21, 15.58, 11.25, 8.32];
var output_lables = [];
var output_values = [];
for(var i=0;i<input_lables.length;i++){
     if(!values[i]){
           output_lables.push(input_lables[i]);
           output_values.push(input_values[i]);
     }        
}      
var myPieChart = new Chart(ctx, {
  type: 'pie',
  data: {
    labels: output_lables,
    datasets: [{
      data: output_values,
      backgroundColor: ['#007bff', '#dc3545', '#ffc107', '#28a745'],
    }],      
  },
});      

if you went to automatic it just enough make a function like this code.

1
votes

According with the documentation you can use the filter parameter in the label

http://www.chartjs.org/docs/latest/configuration/legend.html

and you can make a validation to validate the data and if it is 0 you can return false

Filter a legend Item with Chartjs.org V2.7