ChartJS provides interactive and animated HTML 5 based javaScript charts. We can use these in Lightning components to display charts.
I have created a sample lightning app which display different charts by using salesforce data.
I am going to display opportunities amount(in millions) grouped by forecast category. First of all store the Chartjs file in static resource in order to use it in lightning components.
Download the Chartjs file which I am using from this link Chartjs download
You can download complete code along with static resource from below Github repository and deploy to your org.
Chartjs-in-Lightning-Sample-Code
Below is sample code used to display charts in above snapshot.
Hope this will help!!
I have created a sample lightning app which display different charts by using salesforce data.
I am going to display opportunities amount(in millions) grouped by forecast category. First of all store the Chartjs file in static resource in order to use it in lightning components.
Download the Chartjs file which I am using from this link Chartjs download
You can download complete code along with static resource from below Github repository and deploy to your org.
Chartjs-in-Lightning-Sample-Code
Below is sample code used to display charts in above snapshot.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<aura:component controller="SK_ChartJsCmpController"> | |
<aura:attribute name="ltngChartData" type="Object"/> | |
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/> | |
<div class="slds-grid slds-wrap"> | |
<div class="slds-size--1-of-1 slds-medium-size--1-of-1 slds-large-size--1-of-1" > | |
<div class="slds-card__body slds-card__body_inner" aura:id="lineChartSection"/> | |
</div> | |
<div class="slds-size--1-of-1 slds-medium-size--1-of-1 slds-large-size--1-of-1" > | |
<div class="slds-card__body slds-card__body_inner" aura:id="horrizontalBarChartSection"/> | |
</div> | |
<div class="slds-size--1-of-1 slds-medium-size--1-of-1 slds-large-size--1-of-1" > | |
<div class="slds-card__body slds-card__body_inner" aura:id="pieChartSection"/> | |
</div> | |
</div> | |
</aura:component> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<aura:application extends="force:slds"> | |
<c:SK_ChartJsCmp /> | |
</aura:application> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SK_ChartJsCmpController { | |
public static List<string> bgColorCodesForChart = new List<string>{'#FF6384','#36A2EB','#bed2ce','#0abc70','#f5b022','#e85e7f'}; | |
@AuraEnabled | |
public static ChartDataWrapper findDataSetForChart(){ | |
ChartDataWrapper cdataSet = new ChartDataWrapper(); | |
string queryString = 'SELECT ForecastCategoryName, SUM(Amount) FROM Opportunity GROUP BY ForecastCategoryName '; | |
AggregateResult[] groupedResults = database.query(queryString); | |
integer count =0; | |
for (AggregateResult ar : groupedResults) | |
{ | |
string clabel = string.valueof(ar.get('ForecastCategoryName')); | |
string categorylabel = string.valueof(ar.get('ForecastCategoryName')); | |
decimal amount = (decimal)ar.get('expr0'); | |
amount = amount != null ? (amount/1000000).setScale(2) : 0; | |
cdataSet.labels.add(clabel + '('+string.valueof(amount)+')'); | |
cdataSet.dataValues.add(string.valueof(amount)); | |
if(bgColorCodesForChart[count] != null){ | |
cdataSet.bgColorValues.add(bgColorCodesForChart[count]); | |
count++; | |
} | |
System.debug('ForecastCategoryName:' + clabel); | |
System.debug('Sum amount' + string.valueof(amount)); | |
} | |
return cdataSet; | |
} | |
public class ChartDataWrapper{ | |
@AuraEnabled | |
public list<string> labels{get;set;} | |
@AuraEnabled | |
public list<string> dataValues{get;set;} | |
@AuraEnabled | |
public list<string> bgColorValues{get;set;} | |
public ChartDataWrapper(){ | |
labels =new list<string> (); | |
dataValues = new list<string> (); | |
bgColorValues = new list<string> (); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
({ | |
doInit : function(component, event, helper) { | |
var params ={}; | |
helper.callToServer( | |
component, | |
"c.findDataSetForChart", | |
function(response) | |
{ | |
console.log('apex response :'+JSON.stringify(response)); | |
component.set("v.ltngChartData",response); | |
//display line chart | |
helper.generateChartData(component,"line","lineChartSection"); | |
//display horrizontal bar chart | |
helper.generateChartData(component,"bar","horrizontalBarChartSection"); | |
//display Pie chart | |
helper.generateChartData(component,"pie","pieChartSection"); | |
}, | |
params | |
); | |
} | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
({ | |
callToServer : function(component, method, callback, params) { | |
console.log('Calling helper callToServer function'); | |
var action = component.get(method); | |
if(params){ | |
action.setParams(params); | |
} | |
console.log('****param to controller:'+JSON.stringify(params)); | |
action.setCallback(this, function(response) { | |
var state = response.getState(); | |
if (state === "SUCCESS") { | |
callback.call(this,response.getReturnValue()); | |
}else if(state === "ERROR"){ | |
alert('Problem with connection. Please try again.'); | |
} | |
}); | |
$A.enqueueAction(action); | |
}, | |
loadChart : function(component, chartSection, componentName, params){ | |
console.log('*****load chart called'+chartSection); | |
$A.createComponent( | |
componentName, | |
params, | |
function(chartBox) { | |
//Add the dynamic chart to div | |
if (component.isValid()) { | |
console.log('****creating the chart component'); | |
var targetCmp = component.find(chartSection); | |
targetCmp.set("v.body",[]); | |
var body = targetCmp.get("v.body"); | |
body.push(chartBox); | |
targetCmp.set("v.body", body); | |
} | |
} | |
); | |
}, | |
generateChartData: function (component,chartType,chartDivSectionId){ | |
var cDatask = component.get("v.ltngChartData"); | |
var cmpAttributes = { | |
ltngChartData: cDatask, | |
ltngChartType :chartType | |
} | |
if(cDatask.labels){ | |
this.loadChart( | |
component, | |
chartDivSectionId, | |
"c:SK_ChartJsTemplate", | |
cmpAttributes | |
); | |
} | |
} | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<aura:component > | |
<ltng:require scripts="{!$Resource.SK_Chartjs}" afterScriptsLoaded="{!c.generateChart}"/> | |
<aura:attribute name="ltngChartData" type="object"/> | |
<aura:attribute name="ltngChartType" type="String" default="pie"/> | |
<div class="slds-grid slds-wrap"> | |
<div class="slds-size--1-of-1 slds-medium-size--1-of-1 slds-large-size--1-of-1" > | |
<canvas aura:id="chartdiv" ></canvas> | |
</div> | |
</div> | |
</aura:component> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
({ | |
generateChart : function(component, event, helper) { | |
//for bar chart | |
var pieChartData = component.get("v.ltngChartData"); | |
var chartLabel = component.get("v.ltngChartType") + ':Opportunities Grouped By Forcast Category'; | |
var cdata = { | |
labels: pieChartData.labels, | |
datasets: [ | |
{ | |
label:chartLabel, | |
data: pieChartData.dataValues, | |
backgroundColor: pieChartData.bgColorValues, | |
borderColor:'rgba(62, 159, 222, 1)', | |
fill: false, | |
pointBackgroundColor: "#FFFFFF", | |
pointBorderWidth: 4, | |
pointHoverRadius: 5, | |
pointRadius: 3, | |
bezierCurve: true, | |
pointHitRadius: 10 | |
} | |
] | |
} | |
//Get the context of the canvas element we want to select | |
var ctx1 = component.find("chartdiv").getElement(); | |
var lineChart = new Chart(ctx1 ,{ | |
type: component.get("v.ltngChartType"), | |
data: cdata, | |
options: { | |
legend: { | |
position: 'bottom' | |
}, | |
responsive: true, | |
maintainAspectRatio: false | |
} | |
}); | |
} | |
}) |
Hope this will help!!