Chartjs-Vertical stacked bar chart using SharePoint List

0👍

The code example for your reference:

<div style="width:600px;height:400px;">
    <canvas id="myChart" width="600" height="400"></canvas>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<script type="text/javascript">
var colors = ["#009EA0", "#A7A9AC", "#D15F27", "#BAD80A", "#E0AA0F", "#754760", "#373535"];
var listName = "CL26"; //Data List Name
var xAxisName="Title";
var yAxisName=["Java","Python","SharePoint","DotNet"];
$(document).ready(function() {
    var requestUri = _spPageContextInfo.webAbsoluteUrl +
                  "/_api/Web/Lists/getByTitle('"+listName+"')/items";

    //execute AJAX request
    $.ajax({
        url: requestUri,
        type: "GET",
        headers: { "ACCEPT": "application/json;odata=verbose" },
        success: function (data) {
            var myLabels=[];
            var myDataSets=[];
            $.each(data.d.results, function(i, item) {
                myLabels.push(item[xAxisName]);    
            });
            for(var i=0;i<yAxisName.length;i++){ 
                var myData=[];                  
                $.each(data.d.results, function(j, item) {
                    myData.push(item[yAxisName[i]]);
                });
                myDataSets.push({
                    label:yAxisName[i],
                    backgroundColor:colors[i],
                    data:myData
                });                 
            }
            buildBarChart(myLabels,myDataSets);
        },
        error: function () {
            //alert("Failed to get details");
        }
    });
});

function buildBarChart(myLabels,myDataSets){
    var barChartData = {
        labels: myLabels,
        datasets: myDataSets
    };
    var ctx = document.getElementById('myChart').getContext('2d');
    var myBar = new Chart(ctx, {
            type: 'bar',
            data: barChartData,
            options: {
                title: {
                    display: true,
                    text: 'MyProject'
                },
                tooltips: {
                    mode: 'index',
                    intersect: false
                },
                responsive: true,
                scales: {
                    xAxes: [{
                        stacked: true,
                    }],
                    yAxes: [{
                        stacked: true
                    }]
                }
            }
        });
}   
</script>

enter image description here

Leave a comment