Creating visually appealing Stacked Bar Charts with Google Charts: Adding unique colors to each section of the bar

I have been working on creating a stacked bar chart using the Google API. Each bar will be divided into 3 sections representing Negative, Neutral, and Positive feedback that we have received.

Here is a snippet of my data and options code:

 data = google.visualization.arrayToDataTable([
              ['Category', 'Negative', 'Neutral', 'Positive'],
              ['icon', 10, 800, 5],
              ['colour', 5, 5, 5],
              ['copy', 5, 5, 5],
              ['navigation', 5, 5, 5]
            ]);
        };
   options = {
        isStacked: true,
        width: '100%',
        height: 400,
        hAxis: {title: 'Category', textStyle: {bold : true, fontSize: 24}, titleTextStyle: {color: 'White'}},
        vAxis: {title: 'Responses', textStyle: {bold : true, fontSize: 24}, titleTextStyle: {color: 'White'}}
        };
  var chart = new google.charts.Bar(document.getElementById('categoryChart'));
        chart.draw(data, google.charts.Bar.convertOptions(options));

I am trying to adjust the color scheme by including an array in the options like this:

colors:['red','blue', 'green'].

However, this only assigns the first color (red) to the entire bars instead of individual slices within them.

Do you have any suggestions on how I can control the colors for each part of the bar chart?

Thanks,

Adam

Answer №1

Modifying the color style can be achieved in the following manner :

data = google.visualization.arrayToDataTable([
          ['Category', 'Negative', 'Neutral', 'Positive', { role: 'style' }],
          ['icon', 10, 800, 5, '#b87333'],
          ['colour', 5, 5, 5, 'silver'],
          ['copy', 5, 5, 5, 'gold'],
          ['navigation', 5, 5, 5, 'color: #e5e4e2']
      ]);

Update :

The issue arises in this line :

var chart = new google.charts.Bar(document.getElementById('categoryChart'));

You are using google.charts.Bar instead of google.visualization.ColumnChart

Working example :

google.load('visualization', '1', {
    packages: ['corechart', 'bar']
});
google.setOnLoadCallback(drawBarColors);

function drawBarColors() {
    var data = google.visualization.arrayToDataTable([
        ['Category', 'Negative', 'Neutral', 'Positive'],
        ['icon', 10, 100, 5],
        ['colour', 5, 5, 5],
        ['copy', 5, 5, 5],
        ['navigation', 5, 5, 5]
    ]);

    var options = {
        isStacked: true,
        width: '100%',
        height: 400,
        colors: ['red', 'blue', 'green'],
        hAxis: {
            title: 'Category',
            textStyle: {
                bold: true,
                fontSize: 24
            },
            titleTextStyle: {
                color: 'White'
            }
        },
        vAxis: {
            title: 'Responses',
            textStyle: {
                bold: true,
                fontSize: 24
            },
            titleTextStyle: {
                color: 'White'
            }
        },

    };

    var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
    chart.draw(data, options);
}
  <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  <div id="chart_div"><div>


Reference

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

Guide on transferring the Token from the initial response request to the header of the second request, with the help of Axios in an Ionic React application (Making 2 Post Requests

I am trying to create a user account and save the partner's data simultaneously. The initial axios request is used to create the user and obtain a token in return. I need to pass this token as a header in the second request. Despite implementing &apos ...

What is the process of integrating ES6 modules with app.get in a Node/Express routing application?

After researching the benefits of ES6 export, I made the decision to implement it in a NodeJS/Express project instead of using module exports. The MDN documentation explained that export is used as shown below: export function draw(ctx, length, x, y, color ...

The term 'EmployeeContext' is being utilized as a namespace in this scenario, although it actually pertains to a type.ts(2702)

<EmployeeContext.Provider> value={addEmployee, DefaultData, sortedEmployees, deleteEmployee, updateEmployee} {props.children}; </EmployeeContext.Provider> I am currently facing an issue mentioned in the title. Could anyone lend a hand? ...

Using the tensorflow library with vite

Greetings and apologies for any inconvenience caused by my relatively trivial inquiries. I am currently navigating the introductory stages of delving into front-end development. Presently, I have initiated a hello-world vite app, which came to life throug ...

The sticky navigation and scroll to top features both function perfectly on their own, but when used simultaneously, they do not work

I'm facing an issue with two scripts on my website - when they are separate, they work perfectly fine but together, they don't seem to function properly. What could I be missing here? Script 1: window.onscroll = function() {myFunction()}; var n ...

Creating a canvas element within an iframe: A step-by-step guide

I have a unique situation where I have an iframe containing a DIV element named "pageContainer1". My goal is to insert a canvas element into that specific DIV and then be able to access it in order to draw something on it. Despite my attempts so far, this ...

Is there a way to remove "gsi" from a string and replace it with an empty string in JavaScript?

I need to modify a string by removing the substring gsi and its value. The desired outcome should be: Scenario 1 /product/Abrasives?gsi=1 Expected output /product/Abrasives Scenario 2 /product/Abrasives?query=search&gsi=1 Expected output /product/A ...

Having trouble locating HTML elements by their id when typing into a box using cy.get in Cypress with JavaScript

I am a novice in working with cypress and HTML, and I am currently attempting to enter an address in the specified address field. <input type="text" title="Street Address 1" name="billing[street][]" id="billing:street1" value="" class="input-text " ...

How come my FormData POST request isn't being blocked by CORS policy?

I am facing confusion with one query: why does my POST request, which sends form data from a frontend hosted on a different origin to a backend hosted on a different origin, not get blocked by CORS policy? My Node.js code includes the following: const exp ...

The data from the AJAX response is not appearing on the HTML table within the modal using jQuery

I have a link that, when clicked, opens the modal and calls the ajax method. The modal opens and the ajax method retrieves the response data successfully, but the data is not displayed within the table on my modal. I have tried multiple approaches, but non ...

Display the JSX element only if the other element is empty

My webpage has the following structure: export default function MyBidPage() { return ( <div className="children:mb-4"> <AskToQualifyForm /> <CreateBidSection /> <DocumentsSection /> <AboutB ...

Encountering problem while exhibiting server's response message within a modal popup in Angular 6

I have implemented two custom dialog modals in an Angular component. The objective is to open the appropriate modal and display the response message. The component receives two values as Observables from my services: The name of the modal that needs to ...

Retrieving information from a PHP server using AJAX

Searching for a way to retrieve the posts created by users and load more posts upon user's request. Encountering an Unexpected end of JSON input error when initiating an ajax request in the console. Javascript $("#ajax_load_more").click(function ...

Tips on skipping the need to repeatedly use `@ApiProperty()` for every dto in NestJs-swagger

I'm currently exploring ways to streamline the process of specifying @ApiProperty() for each DTO. I've heard about a method involving the creation of a nest-cli.json file, where if you define Promise<DTO> in your controller within nest-swa ...

Error: myFunction has not been declared

Can anyone figure out what's going on here? http://jsfiddle.net/sVT54/ <button onclick="myFunction()">Click me</button> <p id="demo"></p> function myFunction() { document.getElementById("demo").innerHTML="Hello World"; } ...

How can I get electron to interact with sqlite3 databases?

I've exhausted all my options and still can't get it to function. This error message keeps popping up: https://i.stack.imgur.com/D5Oyn.png { "name": "test", "version": "1.0.0", "description": "test", "main": "main.js", "scripts": { ...

In the solidgauge feature of Highcharts, the color scheme shifts within a specific range

Is there a way to prevent the color distortion in Highcharts solid gauge charts when increasing the pane size? How can I maintain 100% size without breaking the colors? enter image description here Below is the code snippet: const options = { title: { ...

An HTML button generated by a .js file is able to execute a .js function without any issues, but it inadvertently removes all .css styling

Currently grappling with an issue in my JavaScript self-teaching journey that I can't seem to resolve or find examples for. The problem at hand: When the HTML button calls a .js function, it successfully executes the function but also wipes out all C ...

Using jQuery to manipulate the radio button input's alternate content in HTML attributes

How can I use Jquery Attr.Radio Button click to write to the div with id #RadioDesc? <input type="radio" desc="sample description" class="AddText"> <script type="text/javascript"> $( document ).ready( function() { $("radio").click ...

Adjusting the view of an OpenLayers3 map to encompass various vector layers

My OpenLayers3 map includes an OSM Tile layer and one or more Vector layers. I have a function that allows me to zoom into a single layer successfully: vector.addEventListener("change", function() { map.getView().fitExtent(vectorSource.getExtent(), ma ...