Search code examples
javascriptajaxcanvaspie-chartcanvasjs

Hiding labels for CanvasJS chart?


I have a Canvas JS chart and if the values are 0, I'd like to hide the labels. 2 of my datapoints are non-zero. My JavaScript is:

           var chart = new CanvasJS.Chart("chartContainer",
            {
                title:{
                    text: ""
                },
                legend: {
                    maxWidth: 350,
                    itemWidth: 120
                },
                data: [
                {
                    type: "pie",
                    showInLegend: true,
                    toolTipContent: "${y} - #percent %",
                    dataPoints: [
                        { y: debt, indexLabel: "Debt Payments" },
                        { y: housing, indexLabel: "Housing" },
                        { y: utilities, indexLabel: "Utilities" },
                        { y: foodandsupplies, indexLabel: "Food and Supplies"},
                        { y: transportation, indexLabel: "Transportation" },
                        { y: health, indexLabel: "Health"},
                        { y: otherDebts, indexLabel: "Other payments"}
                    ]
                }
                ]
            });
            chart.render();

The outcome of the JavaScript is:

Pie Chart

I would appreciate any help with this. Thanks!


Solution

  • You can hide the indexLabels for dataPoints with zero as y values by going through the chart options and setting the indexLabel as empty string for all such dataPoints.

    Add this code snippet before rendering the chart i.e. chart.render() and it should work fine.

    for(var i = 0; i < chart.options.data[0].dataPoints.length; i++) {
     if(chart.options.data[0].dataPoints[i].y === 0)
      chart.options.data[0].dataPoints[i].indexLabel = "";
    }
    

    Hope it helps.