SharePoint List utilized to create a vertical stacked bar chart

I am currently working on creating a stacked bar chart using SharePoint complex list data with REST and JavaScript. The challenge I'm facing is that I'm having difficulty obtaining the proper data sets.

My scenario is as follows: I have a SharePoint 2013 list with 6 columns. I need to create a bar chart where the x-axis represents column-1 (Project Type) and the y-axis stacks based on column-2 (Technology) by the count of different technologies used. There are 7 project types, 15 technologies, and approximately 200 rows with various combinations.


Project Java Python SharePoint .Net
A        3     5        12       1
B        4     7        6        3
C        0     9        1        0

I have experimented with Chart.js, whether it's chart.js, Google chart.js, or Highcharts.js. All I need is for the data to be dynamic so that whenever a user adds more values to the project column, they are automatically added to the x-axis.

I am fairly new to this concept. Can someone please assist me in accomplishing this task? I would appreciate any help, including code examples. Thank you in advance.

Answer №1

Below is a code snippet provided 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";

    // Sending an 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 Data'
                },
                tooltips: {
                    mode: 'index',
                    intersect: false
                },
                responsive: true,
                scales: {
                    xAxes: [{
                        stacked: true,
                    }],
                    yAxes: [{
                        stacked: true
                    }]
                }
            }
        });
}   
</script>

https://i.sstatic.net/4bwLT.jpg

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

retrieve information at varying intervals through ajax

In my web page, there are two div elements that both fetch server data using AJAX. However, div-a retrieves data every second while div-b retrieves data every minute. How can I adjust the frequency at which each div fetches server data? ...

Issues with Converting JSON to HTML Table using JavaScript

Issues with Converting JSON to HTML Table Using JavaScript I've been trying to create a function that will display the contents of a JSON file in an HTML table. However, I keep getting an undefined error. Despite being able to see the data displayed ...

Is it possible to verify the authenticity of published npm packages by utilizing hashes/checksums?

As I prepare to release an npm package on behalf of my organization, let's call it Organization A, I want our clients to have a means of verifying that the package they are using was indeed released by us. One method to accomplish this is by computing ...

Unleashing the power of RollupJs: A guide to dynamically bundling modules and objects

Is there a way to dynamically bundle a module/object into my RollupJs output file? I have experimented with various options without success in achieving the desired result. Below is a brief sample project that demonstrates what I am trying to achieve. The ...

Utilizing an AngularJS custom filter twice

Experimenting with a custom Angular filter example found at: https://scotch.io/tutorials/building-custom-angularjs-filters#filters-that-actually-filter, my version looks like this: <!DOCTYPE html> <html> <script src="http://ajax.googleapi ...

Fullcalendar feature that restricts users from selecting multiple days for an event

I am using the fullcalendar plugin from http://fullcalendar.io/ and I want to restrict users from creating events spanning multiple days. $('#calendar').fullCalendar({ defaultView: 'agendaWeek', lang: "fr", header: ...

Customize your Jquery UI Calendar with Changing Background Images for Each Month!

How can I change the background of jQuery UI datepicker based on the selected month? I have created 12 classes, each representing a month, and the selected month already has the background. I tried using "onChangeMonthYear: function(year, month, inst) { ...

Postman: Iterating through requests with various input data sets to dynamically generate the request body

I am facing a challenge with my login API request that requires 3 parameters (userName, password, and remember) in the request body. Out of these parameters, userName and password are mandatory, while remember is optional. The input data is being pulled fr ...

Exploring key array filtering in CouchDB for enhanced search capabilities

In my view function, I have the following code: emit([doc.address.country, doc.address.state, doc.address.city], doc); When making a search query, all 3 elements of the array must be filled in, like this: ?key=["US", "NY", "New York"] If I only want to ...

The functionality for selecting text in multiple dropdown menus using the .on method is currently limited to the first dropdown

Having trouble selecting an li element from a Bootstrap dropdown and displaying it in the dropdown box? I'm facing an issue where only the text from the first dropdown changes and the event for the second dropdown doesn't work. <div class="dr ...

Expanding the number of buttons for <ul> in creating a responsive navigation system using Angular

My navigation consists of 8 items (li), and as the resolution shrinks, the items are pushed onto a new line. I am looking to implement a feature where if an item doesn't fit in the navigation anymore, a "MORE" dropdown button appears on the right side ...

Firebase Error: Trying to access properties of null object (indexOf)

Whenever I try to console.log(docSnap), a Firebase error shows up as seen in the image below. Despite attempting various solutions, none have proved effective. https://i.sstatic.net/9R4vE.png useEffect(() => { if (folderId === null) { ...

Using a customized layout, merge AngularJS into Vaadin

I experimented with integrating an angular JS application into Vaadin by utilizing a custom layout as shown below: VerticalLayout mainLayout = new VerticalLayout(); mainLayout.setMargin(true); mainLayout.setWidth("1380px"); setCompositionRoot( ...

What is the best way to invert the positioning of the li elements to move upwards?

https://i.stack.imgur.com/mZaoS.png Seeking assistance on adjusting the height of bars to start from the bottom and go upwards instead of starting from the top position and going downwards. The JavaScript code below is used to generate the li elements and ...

Searching in Datatables does not trigger a table refresh

Currently, I am utilizing the .search() method in Datatables to search for a value in row 0 when a user clicks on a specific button. However, I encountered an issue where if the user wants to go back and view all table entries again by deleting the input t ...

Is there a way to update the Angular component tag after it has been rendered?

Imagine we have a component in Angular with the selector "grid". @Component({ selector: 'grid', template: '<div>This is a grid.</div>', styleUrls: ['./grid.component.scss'] }) Now, when we include this gri ...

What is the mechanism behind the functionality of the .any() method in Python?

Looking to create a script that models the behavior of chemical reactions over time. One key input is an array like this: popul_num = np.array([200, 100, 0, 0]) This array represents the number of molecules for each species within the system. The main fun ...

Unable to access the 'push' property of an undefined value within an array comprising objects

Right now, I am working with an object of arrays that needs to be filled with objects. Here is what I currently have: ... let foo = { "a" : [], "b" : [], "c" : [] } then, let obj = { ... } foo["a"].push(obj); However, when I run this code, I ...

Creating a nested observable in Angular2: A step-by-step guide

Currently, I am exploring a new approach in my Angular2 service that involves using observables. The data source for this service will initially be local storage and later updated when an HTTP call to a database returns. To achieve this dynamic updating of ...

What is the best way to retrieve and utilize various data from a JSON object? Is creating an array necessary for this task?

As a novice, I am currently utilizing $.get to fetch data from a REST API, the JSON response looks like this: [{"id":"1","url":"http:\/\/123.456.78.910\/workforce\/images\/item1.jpg","price":"99","description":"Mobile Phone"}, ...