Build a Chart Based On SharePoint List Data using Chart JS Library

In this article. I have explained how to build custom charts based on sharepoint list using chart JS library

Now am going to create a simple task list in sharepoint after then going to build doughnut/Pie chart based on list data

Let’s get started I have a task list with few information already entered

Task List Template

After that now going to download the chart js library from their CDN

https://cdnjs.com/libraries/Chart.js

You can download it from 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 = []; // Holds the chart label information
        var count = []; // Holds the total count value based on each status

        // Using lodash libary to count data based on "Status" column
        var data = _.map(_.countBy(response, "Status"), function(val, key) {
            return (label.push(key), count.push(val))
        });

        //Initialize the chart 
        var context = document.getElementById("myChart").getContext("2d");
        var myChart = new Chart(context, {
            type: 'doughnut', // type of chart doughnet or pie
            // The data for our dataset
            data: {
                labels: label, // label array collection
                datasets: [{
                    data: count, // count array collection
                    backgroundColor: [
                        'rgb(244, 244, 66)',
                        'rgb(95, 239, 59)',
                        'rgb(219, 40, 13)',
                        'rgb(234, 148, 63)',
                        'rgb(211, 45, 229)',
                    ],
                }]
            },
        });
    })
}

_.countBy It 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 on 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',
                // The data for our dataset
                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!….

Author Profile

Vinodh
Vinodh is a Microsoft MVP for SharePoint (Office Apps and Services) having 5+ years of experience in Microsoft Technologies.

His interest and expertise includes SharePoint Online Development, PowerApps Development, Flows for SharePoint and PowerApps. Single Page Apps/Add ins for SharePoint using React, Angular. SharePoint Farm Management, 2, 3 and upto 6 tier SharePoint Farm Installation and Configuration.

Awards :
Microsoft Most Valuable Professional for SharePoint and Office 365 awarded for the year 2016, 2017 and 2018.
C# Corner Most Valuable Professional for SharePoint and Office 365 awarded for the year 2016, 2017 and 2018.
Technology Expertise :
SharePoint Online, SharePoint 2013, SharePoint 2016 and SharePoint 2019 Preview.
Intranets both Modern and Classic, SharePoint Frameworks Customisation, SharePoint Add-ins, SharePoint single page apps.
Angular 5 with Bootstrap single page apps.
Typescript, JQuery and Javascript.
Micrsoft Flow and Powerapps.
Utilised :
Microsoft Graph API, SharePoint REST, SharePoint PnP JS.
Out of Box :
Consume Content search web parts for internet publishing sites using custom display templates.
Having knowledge on SharePoint workflows and SharePoint Designer workflows.
List customisation using JS Link, JSON Formatting.
Having knowledge in Active directory management services.
Create and configure service applications in SharePoint (MMS, UPSA, SSA).
Configure Outgoing email settings using SMTP Services.

Add a Comment

Your email address will not be published. Required fields are marked *