In this article, I have explained how to build custom charts based on Sharepoint list using chartJS library.
Now I am going to create a simple task list in SharePoint, then I am going to build a doughnut/Pie chart based on list data.
Let’s get started, I have a task list with some information already entered.
After that now I'm going to download the chartjs library from their CDN.
You can download it from the above link.
Create a HTML file in your sharepoint site assets folder and paste the below HTML snippet.
- <canvas id="myChart"></canvas>
Now create a function named GetChartData(); then query the task list using REST API or using SharePoint PNP JS Library and Process the data to render chart inside your content editor or script editor webpart.
- function GetChartData() {
- $pnp.sp.web.lists.getByTitle('My Tasks').items.get().then(function(response) {
-
- var label = [];
- var count = [];
-
-
- var data = _.map(_.countBy(response, "Status"), function(val, key) {
- return (label.push(key), count.push(val))
- });
-
-
- var context = document.getElementById("myChart").getContext("2d");
- var myChart = new Chart(context, {
- type: 'doughnut',
-
- data: {
- labels: label,
- datasets: [{
- data: count,
- backgroundColor: [
- 'rgb(244, 244, 66)',
- 'rgb(95, 239, 59)',
- 'rgb(219, 40, 13)',
- 'rgb(234, 148, 63)',
- 'rgb(211, 45, 229)',
- ],
- }]
- },
- });
- })
- }
_.countBy helps you to calculate the number of items count based on
“Status” Column.
Here we go -- finally we can see the chart has been successfully rendered.
I have made some changes to control the width and height of the chart.
Full Code
- <head>
- <script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/sp-pnp-js/3.0.10/pnp.min.js" type="text/javascript"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" type="text/javascript">
- </script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" type="text/javascript"></script>
- </head>
-
- <body
- <canvas id="myChart" style="height:200px; max-width:400px; margin: 0px auto;"></canvas>
- <script type="text/javascript">
- $(document).ready(function(){
- GetChartData()
- })
-
- function GetChartData(){
- $pnp.sp.web.lists.getByTitle('My Tasks').items.get().then(function(response){
- console.log(response)
- var label = [];
- var count = [];
- var data = _.map(_.countBy(response, "Status"), function(val, key) { return (label.push(key), count.push(val)) });
-
- console.log("data", data);
-
- var context = document.getElementById("myChart").getContext("2d");
- var myChart = new Chart(context, {
- type: 'doughnut',
-
- data: {
- labels: label,
- datasets: [{
- data: count,
- backgroundColor: [
- 'rgb(244, 244, 66)',
- 'rgb(95, 239, 59)',
- 'rgb(219, 40, 13)',
- 'rgb(234, 148, 63)',
- 'rgb(211, 45, 229)',
- ],
- }]
- },
- });
- })
- }
- </script>
- </body>
Happy Coding !