Lightning Chart.js example

In this blog, I am going to show how to use the Chart.js in the lightning component with different types of charts. Using chart.js easy to get started. All that’s required is the script included in your page along with a single  node to render the chart.

Step 1: Add Chart.js to the static resource

Go to this link  and download the latest version of chart.js and upload the static resource

Step 2: Apex Class

Here is the simple apex class which I created to get the aggregate data from the Task__c custom object.

public class TaskManagerChart {
    
    @AuraEnabled
    public static List<DataSet> getAllTasksByStatus(){
        List<AggregateResult> result =  [Select Count(Id) cnt, Status__c from Task__c group by Status__c ];
        List<DataSet> dataSet = new List<DataSet>();
        for(AggregateResult ar:result){
            String status =  (String)ar.get('Status__c') ;
            Integer total =(Integer)ar.get('cnt'); 
            dataSet.add(new DataSet(status ,total));
            
        }
        System.debug('dataSet'+dataSet);
        return dataSet ; 
    }
    
    public class DataSet{
        public DataSet(String label ,Integer count){
            this.label  = label ; 
            this.count = count ;
        }
        @AuraEnabled
        public String label {get;set;}
        @AuraEnabled
        public Integer  count {get;set;}
        
        
    }
    
}

 

Step 3: Lightning Component Pie chart

Here is the simple lightning component that shows the task by status as a pie chart. I am loading the chart.js libraries by using ltng:require and using afterScriptsLoaded method to fetch controller logic

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes" access="global" controller="TaskManagerChart">
    <ltng:require scripts="{!$Resource.Chartjs+ '/Chart.min.js'}"
                  afterScriptsLoaded="{!c.scriptsLoaded}" />
    <canvas id="pie-chart" width="950" height="250"></canvas>
 </aura:component>
({
    scriptsLoaded : function(component, event, helper) {
        var action = component.get("c.getAllTasksByStatus");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                let val = response.getReturnValue() ;
                var labelset=[] ;
                var dataset=[] ;
                val.forEach(function(key) {
                    labelset.push(key.label) ; 
                    dataset.push(key.count) ; 
                });
                new Chart(document.getElementById("pie-chart"), {
                    type: 'pie',
                    data: {
                        labels:labelset,
                        datasets: [{
                            label: "Count of Task",
                            backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9"],
                            data: dataset
                        }]
                    },
                    options: {
                        title: {
                            display: true,
                            text: 'Total Tasks by Status'
                        }
                    }
                });
            }
        });
        $A.enqueueAction(action);
        
    }
})

 

Bar Chart 

Bar charts are created by setting type to bar

 new Chart(document.getElementById("pie-chart"), {
                    type: 'bar',
                    data: {
                        labels:labelset,
                        datasets: [{
                            label: "Count of Task",
                            backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9"],
                            data: dataset
                        }]
                    },
                    options: {
                        title: {
                            display: true,
                            text: 'Total Tasks by Status'
                        }
                    }
                });
            }
        })

 

Polar area chart

A polar area chart is created by setting typepolarArea. Polar area charts are closely related to pie charts, with the difference that in addition to the angles representing the relative size of the data points, the radius of each element is set in relation to its value.

 new Chart(document.getElementById("pie-chart"), {
                    type: 'polarArea',
                    data: {
                        labels:labelset,
                        datasets: [{
                            label: "Count of Task",
                            backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9"],
                            data: dataset
                        }]
                    },
                    options: {
                        title: {
                            display: true,
                            text: 'Total Tasks by Status'
                        }
                    }
                });
            }

 

Doughnut chart

Doughnut charts are created by setting type to doughnut.

   new Chart(document.getElementById("pie-chart"), {
                    type: 'doughnut',
                    data: {
                        labels:labelset,
                        datasets: [{
                            label: "Count of Task",
                            backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9"],
                            data: dataset
                        }]
                    },
                    options: {
                        title: {
                            display: true,
                            text: 'Total Tasks by Status'
                        }
                    }
                });