Creating a visual representation of data using Google Charts to display a stacked bar chart

I wrote a script to display a stacked Google chart using JSON data stored on the wwwroot directory -

     <html>
<head>
    <title>DevOps Monitoring Application</title>
    <link rel="icon" type="image/png" href="https://icons.iconarchive.com/icons/martz90/circle/256/plex-icon.png" />
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <style>
        tr > th::first-line {
            font-size: 1.5em;
            font-weight: bolder;
            text-decoration: underline;
        }
    </style>
    <script type="text/javascript">
        google.charts.load("current", {
            packages: ["corechart"]
        }).then(function () {
            $.ajax({
                type: "GET",
                url: "http://localhost/TestExecutionResult.json",
                dataType: "json"
            }).done(function (jsonData) {

                var data = new google.visualization.DataTable();
                data.addColumn('string', 'Task');
                data.addColumn('number', 'Test case execution time');

                $.each(jsonData, function (key, value) {
                    data.addRow([key, parseInt(value)]);
                });


                var options = {
                    title: 'DevOps Monitoring Chart',
                    isStacked: true,
                    legend: { position: 'bottom', maxLines: 3, textStyle: { fontSize: 6 } },
                    bar: { groupWidth: "50%" },
                    hAxis: {
                        format: 'HH:mm', gridlines: { count: 50 },
                        slantedText: false, slantedTextAngle: 45, textStyle: { fontSize: 11 }
                    },
                    vAxis: {
                        title: 'Total execution time (seconds)',
                        viewWindow: {
                            max: 30,
                            min: 0
                        }
                    }
                };

                var chart = new google.visualization.ColumnChart(document.getElementById('barchart'));
                chart.draw(data, options);
            }).fail(function (jqXHR, status, errorThrown) {
                console.log(jqXHR, status, errorThrown)
                // add fail callback
                alert('error: ' + errorThrown);
            });
        });
    </script>

   
</head>

<body>
    <table border="1">
        <tr>
            <td>
                <ul class="breadcrumb">
                    <li>
                        <u><a href="https://example/TestExecutionResultPOD1.zip">Logs</a></u>
                    </li>
                    <li>
                        <u><a id="Release link">Release Link</a></u>
                    </li>
                    <li>
                        <h id="TestLogFileName">
                            Last 5 Results: <select>
                                <option value="--Select Results--">--Select Results--</option>
                                <option value="Test Run at 9:30am">Test Run at 9:30am</option>
                                <option value="Test Run at 9:00am">Test Run at 9:00am</option>
                                <option value="Test Run at 8:30am">Test Run at 8:30am</option>
                                <option value="Test Run at 8:00am">Test Run at 8:00am</option>
                                <option value="Test Run at 7:30am">Test Run at 7:30am</option>
                            </select>
                        </h>
                    </li>

                </ul>
                <div id="LastSuccessfulRun" style="font-size:12px;color:green;margin-top: -15px;margin-bottom: 10px;padding-left: 5px;">Last successful run at: 06-03-2022 09:43:31</div>
                <div id="barchart" style="width: 1000px; height: 600px"></div>
            </td>
    </table>
</body>
</html>

The JSON data includes the following information -

   {"NewAdvisorAccountCreation": 4, "AccountActivation": 13, "OrganizationCreationForAdvisor": 31, "AddingWidgetForDashboard": 0}

However, the chart displays as a simple column chart instead of a stacked column chart. How can I create a single column chart with these 4 values stacked on top of each other in different colors? The legend should include the 4 keys from the JSON data corresponding to the 4 values. Any guidance or tips would be greatly appreciated. Thank you!

Answer №1

The issue lies in the fact that you are generating a new row for every "column".

This revised code should resolve the problem:

var columns = ['Test Execution'], row = ["test execution X"];

$.each(jsonData, function (key, value) {
    columns.push(key);
    row.push(value);
});

var data = google.visualization.arrayToDataTable([
    columns,
    row,
]);

Your JSON represents the data for a single row. To tackle this, we identify and assign a label to that particular row (in my sample it's "test execution X") and iterate through the JSON to incorporate columns and values for each entry.

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

Pagination malfunction on AngularJS md-data-table is causing issues

I have been working on a project that involves retrieving data from an API and displaying it in a table. I am using AngularJS and the md-data-table library by Daniel Nagy. Following the setup instructions, I was able to display my data successfully. Howeve ...

Capturing the unknown elements in a deeply nested array

I'm trying to create a helper function that will return 0 if an element in a nested array is undefined. The issue I'm facing is that when the first index fails and returns undefined, the function should catch errors at subsequent indexes but it&a ...

Pause for a moment before commencing a fresh loop in the FOR loop in JavaScript

Behold, I present to you what I have: CODE In a moment of curiosity, I embarked on creating a script that rearranges numbers in an array in every conceivable way. The initial method I am working with is the "Selection mode", where the lowest value in th ...

A guide to accessing items imported from a glb file within the Babylon JS game engine

When I use the BABYLON.SceneLoader.ImportMesh() method to load a .glb file created in Blender, one of the objects is named Cube.003. Surprisingly, after calling the method, Cube.003 is not included in the scene.meshes array. It does show up in the scene ...

Tips for setting a new key and value for an existing object in TypeScript

As I transition from JavaScript to TypeScript, I am currently working on creating a Discord bot using TypeScript to familiarize myself with the environment. However, I encountered an error when attempting to add new keys to an object that was previously cr ...

Inquiring about socket.io: How can an io emit its own signal?

I am currently working on implementing the emit event in an express router, and I'm attempting to pass a global.io variable. However, I've encountered an issue where despite adding the following code: io.emit('join','Tudis' ...

Custom sorting in JavaScript

I have a specialized sorting method that is defined as follows sortArrayBy: function(a, b, sortKey) { if (a[sortKey] < b[sortKey]) return -1; if (a[sortKey] > b[sortKey]) return 1; return 0; }, I am looking to enhance it ...

Using Vue.js to mark a checkbox as selected

I've searched extensively and tried various combinations, but I'm unable to initialize my checkboxes as checked. For example: <ul class="object administrator-checkbox-list"> <li v-for="module in modules"> <label v-bin ...

Ways to initialize Nested Arrays in Angular applications

I have been experimenting with some code on Codepen. I am trying to load JSON data from a service and then use ng-repeat to display the arrays. The issue I'm facing is that while the first array loads successfully, the nested array "data.cities" is n ...

What alternative methods can be used to render a React component without relying on the ReactDOM.render

Can a React component be rendered simply by referencing it with its name? For example: <div> <MyComponent/> </div> In all the tutorials and examples I've seen, ReactDOM.render function is used to render the component onto the ta ...

There seems to be an issue with the bootstrap datepicker as it is throwing an error stating that $(

Currently in the process of developing a web application using AngularJS with MVC, I have integrated Bootstrap's datepicker into my project, Here is the code snippet: <div class="container"> <div class="row"> <div class=& ...

How to present MongoDB data on the frontend using Node.js without relying on a framework

As someone with experience in HTML, CSS, and JavaScript, I am new to Node.js and server-side programming. Although I can serve HTML pages using FileSystem and the request.url stream in NodeJS, I need assistance as I navigate through my first server-side la ...

Incorporate a new element into your webpage using an AJAX call in Symfony 3, all without

I am currently working on implementing Symfony forms within a modal using AJAX to prevent page reloading every time an add/remove or update action is submitted. However, I am not very familiar with AJAX and unsure how to proceed. Can anyone provide guidanc ...

Allow users to copy and paste on a website where this function is typically restricted

Just wanted to mention that I have very little coding knowledge, so I appreciate your patience. I'm attempting to paste something onto a site that doesn't allow it. Here is the link to the javascript they used to block it: A friend of mine recom ...

Leveraging Angular CLI in conjunction with the newest AspNetCore Angular 4 Single Page Application template

I'm currently experimenting with using Angular CLI alongside the latest JavaScriptServices AspNetCore Angular Spa template. In the past, I would simply copy and paste a .angular-cli.json file into my project's root directory, change "root" to "C ...

Raycasting in Three.js is ineffective on an object in motion

Working on a project that combines three.js and typescript, I encountered an issue while attempting to color a sphere by raycasting to it. The problem arises when the object moves - the raycast doesn't seem to acknowledge the new position of the objec ...

An issue occurred while evaluating the Pre-request Script: Unable to access the 'get' property of an undefined object

I need help accessing the response of my POST request in Postman using a Pre-request Script. Script below : var mobiles = postman.environment.get("mobiles"); if (!mobiles) { mobiles =["8824444866","8058506668"]; } var currentMobile = mobiles. ...

Creating a Copy of an Object in JavaScript that Automatically Updates When the Original is Changed

I am in the process of developing a planner/calendar website with a repeat feature. var chain = _.chain(state.items).filter({'id': 1}).head().value(); console.log(chain); After filtering one object, I am wondering how to create a duplicate of c ...

Generate radio buttons in a model loop in Vue.js based on names automatically

I am attempting to generate a model for each radio button using the inputname as the identifier. My approach involves looping through the array of objects to identify instances where more than one inputname is present, and then converting this value into a ...

When you click, apply the hidden class to all the div elements

Is there a way to apply the .hide class to all .slide divs whenever the .option button is clicked? If so, how can I modify my JavaScript code so that all .slide divs receive the .hide class (if they don't already have it) upon clicking the .option bu ...