Skip to content

Instantly share code, notes, and snippets.

@jenishshingala
Last active August 29, 2015 14:27
Show Gist options
  • Save jenishshingala/19c055cc718625244e84 to your computer and use it in GitHub Desktop.
Save jenishshingala/19c055cc718625244e84 to your computer and use it in GitHub Desktop.
D3 Chart Example
/*
* Author: Jenish Shingala
* Description:Donut Chart Controller/
*
*/
public class donutChartController {
Public List<AggregateResult> lstOfOpprotunity{get;set;}
Public String Jsondata{get;set;}
public donutChartController(){
//Query on opprtunity to get AggregateResult
lstOfOpprotunity = [Select count(Id), StageName from Opportunity Group By StageName];
//Serialize query results and store into string to pass to VF page.
Jsondata = JSON.serialize(lstOfOpprotunity);
system.debug('JSon String$$$'+Jsondata);
}
}
<!--
* Author: Jenish Shingala
* Description: Simple D3 Donut Chart.
-->
<apex:page controller="donutChartController" sidebar="true" >
<!--Difine Jquery-->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!--Include All D3 Libraries-->
<apex:includeScript value="{!$Resource.d3}"/>
<apex:includeScript value="{!$Resource.nv_js}"/>
<apex:stylesheet value="{!$Resource.nv}"/>
<style>
#chart svg{
height: 600px;
width:400px;
}
.nvtooltip h3{
font-size: 17px !important;
}
</style>
<apex:form>
<!--Donut Chart Division-->
<center>
<div id="chart">
<svg></svg>
</div>
</center>
</apex:form>
<!--Simple Donut Chart Script-->
<script>
/*Code to draw Donut Chart*/
var piechartdata = new Array();
nv.addGraph(function(){
var chart = nv.models.pieChart()
.x(function(d) { return d.label })
.y(function(d) { return d.value })
.showLabels(true)
.labelType("value")
.donut(true)
.donutRatio(0.35);
d3.select("#chart svg")
// pass Json array here to fill the data.
.datum(piechartdata)
.transition().duration(350)
.call(chart);
return chart;
});
//Reference controller query results here and store into variable.
var listofopportunity = '{!Jsondata}';
//Parse String
var parsedresults = JSON.parse(listofopportunity);
//Iterate through result and Push these into array.
for(var i=0;i<parsedresults.length;i++){
piechartdata.push({"label":parsedresults[i].StageName,"value":parsedresults[i].expr0});
}
</script>
</apex:page>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment