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

Consolidate HTML project into a unified HTML file

In my current project, I am working with a static HTML report that is organized in the structure outlined below: 1.css 2.font 3.js 4.pages 5.attachments 6.index.html I would like to know how I can combine all these elements to create a unified 'repor ...

Comparing strings with if-else statement

I am having trouble comparing strings in this array. For some reason, the strings are never equal. var person = ["Sam", "John", "Mary", "Liz"]; var searchedName = prompt("Enter name"); var resultMessage = ""; for (index in person) { var currentName = ...

Accessing table cell value when clicked using JavaScript or jQuery

I am currently working on an ASP.NET MVC application where I have a table displaying records from the database in razor code. My goal is to extract the record ID "FeeZoneID" from a cell value when the delete link in the last column is clicked, and then t ...

Top method for transferring server (C# / Razor) data to an AngularJS application

In our use of DNN, we often encounter the need to pass specific context values (such as page id or module-on-page-id) into an AngularJS application. While we have established our own conventions for achieving this, we are interested in hearing about how ot ...

Tips for making a horizontal grid layout with three items in each row

I have a scenario where I need to render a group of Player components using map() loop, and I want them to be displayed horizontally side by side using a Grid component from material-ui. Currently, the components are rendering in a vertical layout: https ...

Numerous applications of a singular shop within a single webpage

I have a store that uses a fetch function to retrieve graph data from my server using the asyncAction method provided by mobx-utils. The code for the store looks like this: class GraphStore { @observable public loading: boolean; @observable ...

Module or its corresponding type declarations not found in the specified location.ts(2307)

After creating my own npm package at https://www.npmjs.com/package/leon-theme?activeTab=code, I proceeded to set up a basic create-react-app project at https://github.com/leongaban/test-project. In the src/index.tsx file of my react app, I attempted to im ...

What is the best way to access event.target as an object in Angular 2?

Apologies for my limited English proficiency. . I am trying to write code that will call myFunction() when the user clicks anywhere except on an element with the class .do-not-click-here. Here is the code I have written: document.addEventListener(' ...

Instead of using a string in the createTextNode() function, consider utilizing a variable

I am attempting to use JavaScript to add another list item to an unordered list. I want the list item to display dynamic content based on a pre-existing variable. While I can successfully append a list item by using a string, things go awry when I try to i ...

When using window.location.href and location.reload(), the updated page content from the server is not loaded properly

Currently, I am working on a form that is being updated via an AJAX call. Once the AJAX call successfully completes, I want to reload the page in order to display the new changes. Even though I tried using location.reload() and window.location.href after ...

Utilizing dropbox.js in combination with OAuth 1: A step-by-step guide

I'm in the process of revamping a website that already exists, and although I have the code from the previous version, I'm encountering challenges replicating certain functionalities in the new iteration. Here's the situation: The user is ...

Having trouble with the lodash find function in my Angular application

npm install lodash npm install @types/lodash ng serve import { find, upperCase } from 'lodash'; console.log(upperCase('test')); // 'TEST' console.log(find(items, ['id', id])) // TypeError: "Object(...)(...) is un ...

Dealing with 'ECONNREFUSED' error in React using the Fetch API

In my React code, I am interacting with a third party API. The issue arises when the Avaya One-X client is not running on the target PC, resulting in an "Error connection refused" message being logged continuously in the console due to the code running eve ...

Obtain an array of responses using jQuery ajax and pass it to PHP

I'm working on a project where I need to populate a table from MySQL based on a selection made in a select box using jQuery AJAX. Currently, this is the jQuery code that I have written. I am able to display the result in an alert box, but I am uncerta ...

Methods to prompt a user to select an option using Bootstrap

I have been struggling with this problem for hours and it's really starting to frustrate me! Currently, I am incorporating Twitter Bootstrap along with bootstrap-min.js. This is the code snippet in question: <select id="assettype" name="assettyp ...

Using jQuery to insert PHP code into a <div> element

In our capstone project, I'm looking to implement a dropdown calendar feature. I initially attempted to use ajax within a dropdown Bootstrap 4, but encountered issues with collapsing. As an alternative, I am considering utilizing the include method. A ...

Universal Module Identifier

I'm trying to figure out how to add a namespace declaration to my JavaScript bundle. My typescript class is located in myclass.ts export class MyClass{ ... } I am using this class in other files as well export {MyClass} from "myclass" ... let a: M ...

Utilizing a React Hook to set data by creating a pure function that incorporates previous data using a thorough deep comparison methodology

I have come across the following code snippet: export function CurrentUserProvider({ children }) { const [data, setData] = useState(undefined); return ( <CurrentUserContext.Provider value={{ data, setData, }} & ...

Utilize Google Tag Manager to search and substitute characters within a variable

Within my GTM setup, I have a CSS selector variable in the DOM. This variable pertains to real estate and specifically represents the price of a listing. My goal is to eliminate the characters ($) and (,) from this variable as part of meeting the requireme ...

Accordion featuring collapsible sections

Looking to build an accordion box using Javascript and CSS. The expanded section should have a clickable link that allows it to expand even further without any need for a vertical scroll bar. Any ideas on how this can be achieved? Thank you ...