Utilizing array indices/variables for dynamic labels on an Animated Google Bar Chart

My database contains multiple tables, and I am looking to utilize Google Charts to display this data. I want the chart to have smooth animations, so I came across a helpful code snippet that I found online and am currently tweaking it to fit my needs.

Since each table in my database has a different number of columns, I am uncertain about how many bars the chart should include until an ajax query is executed (up to a maximum of 5).

I plan to retrieve the data through an ajax request, return it as an array, then calculate the number of columns based on the items in the array. For demonstration purposes, here is a sample dataset:

var Columns = ['Tracker', '1', '2', '3'];
var Information = ['A', 475, 450, 190];

However, when attempting to use the identifier to fetch the column label, the chart malfunctions.

Below, you can find the code snippet along with a link to a related jsfiddle where the issue can be observed. Any insights on what might be causing this problem would be greatly appreciated.

Moreover, if anyone can suggest a more efficient approach without repeating code or using unnecessary if clauses – as I seem unable to come up with one myself for some reason – please feel free to share your thoughts.

Jsfiddle Link

Code Section:

function drawVisualization() {
// Setting up the data table.
var Columns = ['Tracker', '1', '2', '3'];
var Information = ['A', 475, 450, 190];
//var Columns1 = Columns[1]; // Uncomment this line and comment out the following line to see the error
var Columns1 = 1;
var NumColumns = Columns.length - 1;
//alert(Columns1); // To check the value of Columns1
for (index = 1; index < Columns.length; ++index) {
var ColumnName = Columns[index];
var CorrespondingData = Information[index];

}

var data = google.visualization.arrayToDataTable([
    Columns,
    Information
]);

// Using a DataView to initialize all values in the dataset for the initial draw
var view = new google.visualization.DataView(data);
if (NumColumns == 1) {
view.setColumns([0, {
    type: 'number',
    label: data.getColumnLabel(Columns[1]),
    calc: function () {return 0;}
}]);
}else if (NumColumns == 2) {
view.setColumns([0, {
    type: 'number',
    label: data.getColumnLabel(Columns[1]),
    calc: function () {return 0;}
}, {
    type: 'number',
    label: data.getColumnLabel(Columns[2]),
    calc: function () {return 0;}
}]);

}else if (NumColumns == 3){

view.setColumns([0, {
    type: 'number',
    label: data.getColumnLabel(Columns1), // Issue arises if Columns1 is set to Columns[1]
    calc: function () {return 0;}
}, {
    type: 'number',
    label: data.getColumnLabel(2),
    calc: function () {return 0;}
}, {
    type: 'number',
    label: data.getColumnLabel(3),
    calc: function () {return 0;}
}]);
}
// Creating and displaying the visualization.
var chart = new google.visualization.ColumnChart(document.getElementById('visualization'));

var options = {
    title:"Sub-Region vs Region vs Budget",
    legend: 'bottom',
    hAxis: {
        title: ""
    },
    animation: {
        duration: 1000
    },
    vAxis: {
        minValue: 0,
        maxValue: 600
    }
};

var runOnce = google.visualization.events.addListener(chart, 'ready', function () {
    google.visualization.events.removeListener(runOnce);
    chart.draw(data, options);
});

chart.draw(view, options);

$(window).resize(function() {
    chart.draw(data, options);
});
}
google.load('visualization', '1', {packages: ['corechart'], callback: drawVisualization});

Answer №1

After solving this issue myself, I wanted to share my solution for others facing the same problem. The confusion arose from misinterpreting the following line:

label: data.getColumnLabel(1),

I mistakenly thought that it referred to the column labeled as (1) in the original column names. However, in reality, (1) indicates the column number. For example, if the first column was named "A," getColumnLabel(1) would return "A."

To achieve what I intended, simply follow these steps:

function drawVisualization() {
// Create and fill the data table.
var Columns = ['Tracker', 'A', 'B', 'C'];
var Information = ['A', 475, 450, 190];
var NumColumns = Columns.length - 1;

var data = google.visualization.arrayToDataTable([
    Columns,
    Information
]);

// Use a DataView to zero-out all values in the dataset for the initial draw
var view = new google.visualization.DataView(data);
if (NumColumns == 1) {
view.setColumns([0, {
    type: 'number',
    label: data.getColumnLabel(1),
    calc: function () {return 0;}
}]);
} else if (NumColumns == 2) {
view.setColumns([0, {
    type: 'number',
    label: data.getColumnLabel(1),
    calc: function () {return 0;}
}, {
    type: 'number',
    label: data.getColumnLabel(2),
    calc: function () {return 0;}
}]);
} else if (NumColumns == 3) {
view.setColumns([0, {
    type: 'number',
    label: data.getColumnLabel(1),
    calc: function () {return 0;}
}, {
    type: 'number',
    label: data.getColumnLabel(2),
    calc: function () {return 0;}
}, {
    type: 'number',
    label: data.getColumnLabel(3),
    calc: function () {return 0;}
}]);
}

// Create and display the visualization.
var chart = new google.visualization.ColumnChart(document.getElementById('visualization'));

var options = {
    title: "Sub-Region vs Region vs Budget",
    legend: 'bottom',
    hAxis: {
        title: ""
    },
    animation: {
        duration: 1000
    },
    vAxis: {
        minValue: 0,
        maxValue: 600
    }
};

var runOnce = google.visualization.events.addListener(chart, 'ready', function () {
    google.visualization.events.removeListener(runOnce);
    chart.draw(data, options);
});

chart.draw(view, options);

$(window).resize(function() {
    chart.draw(data, options);
});
}
google.load('visualization', '1', {packages: ['corechart'], callback: drawVisualization});

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

Final day of the month (without a time stamp)

Looking to generate two dynamic dates in HTML, JavaScript, and jQuery with the format yyyy/mm/dd. One should display the last day of the previous month, and the other the last day of the current month. Does anyone have a solution using these technologies? ...

Abbreviating Column Labels in Google Visualization

Is there a way to use the google visualization API to display column headers in an abbreviated form in a table, but show the full labels in a pie chart using the same dataset? Check out this snippet of JavaScript: //create the dashboard and table chart ...

Utilizing a Stateflow chart in conjunction with the C Action Language, it is possible to efficiently set array values in order to generate a

Excuse me for what might seem like a silly question, but I'm struggling to set my array variable in a stateflow chart using C Action Language. When working with C language, I usually define my static array with all the values like this: "A[]={1,3,2}; ...

What is the process for including an additional button in the DateTimePicker feature of material UI?

I'm currently utilizing DateTimePicker in my React application. https://i.sstatic.net/ShyTE.png I wish to incorporate a Clear button positioned to the left of the Cancel Button. import { MuiPickersUtilsProvider, DateTimePicker } from "@material-ui/ ...

Adding a div both before and after on window resize

I am facing a challenge where I need to insert each div with a class of "top" into the div with a class of "blurb". However, when I attempt to do this, it results in multiple repeated elements causing the page to crash. Below is the code snippet: <di ...

Alpine declined the action of toggling a list with x-show

My goal is to create a toggleable list of items using Alpine & x-show. I want the list to be visible when the page loads and allow the user to toggle it as needed. Although the button works correctly and the JavaScript is set up properly, the list itself d ...

Unlocking the power of styling tags in React.js

To modify the background color based on the page width, we need to have access to the styles in order to conditionally write the code. If we were to accomplish this using JavaScript, the code would look like: document.getElementById("number1").style.ba ...

Instructions on refreshing a webpage after choosing a sorting option using the onchange attribute

I'm encountering a small issue where the page won't refresh when I select a parameter from a dropdown list. Strangely, when I tested it on a separate document, there was no problem. I suspect Bootstrap may be causing a block somewhere. As someone ...

Any idea how to dynamically insert rows and columns into a table or div element?

Can anyone assist me with this task? I have successfully completed the visual process I intended to do. How can I achieve this structure using AngularJS? The data will be stored in Json format. When the "+" symbol is clicked in a certain direction, the fi ...

You can see through the menus as if they were made of

I'm in need of assistance to understand why the pull down menus (buildings, BV Mail) on certain pages are appearing as transparent while on others they are not. The website address is www.bv340.com. Feel free to ask if you require any additional det ...

Disregard the need for synchronization with $http, but remember to consider it for

Is there a way to prevent synchronization with HTTP requests in an Angular app? I am working on a form that should be disabled while the POST request is in progress. I want to write specifications to ensure that the form remains disabled during this time. ...

JavaScript: Arranging the columns in a two-dimensional array based on the elements in a specific row

Here is an example of an array: [[ 'Table', 'Column A', 'Column B', 'Column C'], [ 'Row 1', 10, 5, 7 ], [ 'Row 2', 20, 15, 50 ], [ 'Row 3', 8, 13, 3 ]] I am looking to rearrange ...

The child_process in Node is attempting to utilize /usr/bin/zsh, but unfortunately, it is unable to do so because

Recently, I've been encountering issues with several npm commands failing, accompanied by an error message that looks like this: npm ERR! code ELIFECYCLE npm ERR! syscall spawn /usr/bin/zsh npm ERR! file /usr/bin/zsh npm ERR! path /usr/bin/zsh npm ER ...

Error encountered in Intellij for Typescript interface: SyntaxError - Unexpected identifier

I am currently testing a basic interface with the following code: interface TestInterface { id: number; text: string; } const testInterfaceImplementation: TestInterface = { id: 1, text: 'sample text' }; console.log(testInterface ...

Using Jquery to extract data from an array stored in a textarea

Is there a way for me to paste the following code snippet inside a textarea and then access it as a common variable in my script? var cars = new Array(new Array(3), new Array(3)); cars[0][0] = 'FORD'; cars[0][1] = 'Focus'; cars[0][2] = ...

Add a new item to an array in Angular 2 when a click event occurs

I'm trying to add a new list item (which comes from an API) when a button is pressed, but I'm not sure how to do it. Can anyone provide some guidance? Here's the code: <ul> <li *ngFor="let joke of jokes">{{joke.value}}</li> ...

Create an Interactive Menu Using JSON Data

Looking for guidance with angularjs as a beginner, I'm interested in creating a dynamic menu using JSON array. { "Pages": [{ "PageId": 1, "PageTitle": "Home", "PageContent": "Home Page Content", "MenuType": "MainMenu", "ParentMenu": null, "PageStatu ...

Utilizing AngularJS with an extensive collection of JSON data

Currently, I am working on developing an application that utilizes a Parent-Child hierarchy by incorporating AngularJs to connect the information retrieved from the RESTFUL web service with the user interface. To demonstrate, here is an example of the JSO ...

Updating the parent component in React when the child component is updated: A step-by-step guide

I am currently working on a child component that consists of four checkboxes with values ranging from 1 to 4. The challenge I am facing is that every time a user clicks on one of the checkboxes, it should pass the respective value to my API to retrieve ite ...

Display a Bootstrap input button group addon, where the first button has rounded corners only after the second button has been hidden

I am working on a button group and need to hide the second button dynamically. However, I am facing an issue where the first button has a 90° border. How can I adjust the code below to display button 1 with a rounded border? If I decide to hide "button ...