Using Google Chart API to create stacked bar charts with annotations using symbols

I am trying to annotate the bars in my stacked bar chart with currency symbols for profit and costs.

While I have been able to successfully annotate the bars without currency symbols, I am facing difficulties in displaying them with the $ prefix. Can anyone help me figure this out?

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
google.charts.load("current", {
packages: ["corechart"]
});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {

var bar_chart_data = [
["Material", "Cost", "Profit", { role: 'style' },{ role: 'style' }],
["A", 100, 25, 'color: #F9F528','color: #0ACB53'],
["B", 4.2, 1.764, 'color: #F9F528','color: #0ACB53'],
["C", 110, 46.199999999999996, 'color: #F9F528','color: #0ACB53'],
["D", 7.56, 3.1752, 'color: #F9F528','color: #0ACB53'],
["E", 4.24, 1.7808, 'color: #F9F528','color: #0ACB53'],
["F", 0.8, 0.336, 'color: #F9F528','color: #0ACB53'],
["G", 2, 0.84, 'color: #F9F528','color: #0ACB53'],
["H", 0.8, 0.336, 'color: #F9F528','color: #0ACB53'],
]

var data = google.visualization.arrayToDataTable(bar_chart_data);

var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}, 3, 
2, {
calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation"
}, 4 

]);

var options = {
title: "Live individual material cost break-up (%)",
width: 600,
height: 400,
bar: {
groupWidth: "95%"
},
legend: {
position: "none"
},
isStacked: 'percent',
hAxis: {
title: 'Percentage',
textStyle: {
fontSize: 8,
fontName: 'Muli',
bold: false,
},

titleTextStyle: {
fontSize: 12,
fontName: 'Muli',
bold: true,
}
},

vAxis: {
title: 'Material',
textStyle: {
fontSize: 10,
bold: false
},
titleTextStyle: {
fontSize: 12,
bold: true
}
}, 

};
var chart = new google.visualization.BarChart(document.getElementById("material_bar_chart"));
chart.draw(view, options);
}

</script>
  </head>
  <body>
    <div id="material_bar_chart" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Answer №1

Utilize the NumberFormat class provided by Google.

You can define a pattern and then format each data column accordingly.

    var formatCurr = new google.visualization.NumberFormat({pattern: '$#,##0'});
    formatCurr.format(data, 1);
    formatCurr.format(data, 2);

Check out the working example snippet below...

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
google.charts.load("current", {
packages: ["corechart"]
});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {

var bar_chart_data = [
["Material", "Cost", "Profit", { role: 'style' },{ role: 'style' }],
["A", 100, 25, 'color: #F9F528','color: #0ACB53'],
["B", 4.2, 1.764, 'color: #F9F528','color: #0ACB53'],
["C", 110, 46.199999999999996, 'color: #F9F528','color: #0ACB53'],
["D", 7.56, 3.1752, 'color: #F9F528','color: #0ACB53'],
["E", 4.24, 1.7808, 'color: #F9F528','color: #0ACB53'],
["F", 0.8, 0.336, 'color: #F9F528','color: #0ACB53'],
["G", 2, 0.84, 'color: #F9F528','color: #0ACB53'],
["H", 0.8, 0.336, 'color: #F9F528','color: #0ACB53'],
]

var data = google.visualization.arrayToDataTable(bar_chart_data);

    var formatCurr = new google.visualization.NumberFormat({pattern: '$#,##0'});
    formatCurr.format(data, 1);
    formatCurr.format(data, 2);

var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}, 3,  
2, {
calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation"
}, 4 
]);

var options = {
title: "Live individual material cost break-up (%)",
width: 600,
height: 400,
bar: {
groupWidth: "95%"
},
legend: {
position: "none"
},
isStacked: 'percent',
        hAxis: {
                  title: 'Percentage',
                  textStyle: {
                     fontSize: 8,
                     fontName: 'Muli',
                     bold: false,
                  },
                  
                  titleTextStyle: {
                     fontSize: 12,
                     fontName: 'Muli',
                     bold: true,
                  }
               },
               
               vAxis: {
                  title: 'Material',
                  textStyle: {
                     fontSize: 10,
                     bold: false
                  },
                  titleTextStyle: {
                     fontSize: 12,
                     bold: true
                  }
               }, 

};
    var chart = new google.visualization.BarChart(document.getElementById("material_bar_chart"));
    chart.draw(view, options);
}

</script>
  </head>
  <body>
    <div id="material_bar_chart" style="width: 900px; height: 500px;"></div>
  </body>
</html>

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

Adjusting the zoom level in leaflet.js ImageOverlay will cause the marker

Using ImageOverlay to display an image as a map with Leaflet.js, but encountering issues with marker positions shifting when changing the zoom level. Followed instructions from this tutorial, and you can find a code pen example here. // Code for markers ...

Why is it impossible for me to delete the class / property of this object?

Within a series of nested divs, there are additional divs containing multiple imgs. The goal is to cycle through these images using CSS transitions. To achieve this, a JavaScript object was created to track the divs, sub-divs, and images. Three arrays were ...

"Troubleshooting a callback problem in jQuery involving JavaScript and AJAX

UPDATE3 and FINAL: The problem has been resolved with the help of Evan and meder! UPDATE2: To clarify, I need the existing function updateFilters(a,b) to be called, not created. My apologies for any confusion. The issue with the code below is that udpate ...

Is it possible to dynamically override inline styles?

My HTML code is as follows: <div title="remove css"style="position:relative;">Remove my style</div> After the page loads, I need to completely remove the position style attribute. Due to limitations, I cannot override the CSS. Is there a way ...

Sending data from a parent component to a child component through a function

In the process of developing an app, I have implemented a feature where users must select options from four dropdown menus. Upon clicking the "OK" button, I aim to send all the selections to a child component for chart creation. Initially, I passed the sel ...

Implementing AngularJS drag and drop functionality in a custom directive

I am in search of an example that demonstrates similar functionality to the HTML5 File API using Angular-js. While researching directives for Angular 1.0.4, I found outdated examples that heavily rely on DOM manipulation. Here is a snippet of the pure Ja ...

Receive the most recent query in a Nuxt plugin following the completion of page loading

So, here's the issue - I have a plugin containing some functions that are supposed to update URL queries. However, every time I run $global.changePage(2) or $global.changeLimit(2), the console.log(query) outputs an empty object and doesn't show t ...

How can I limit auto-search results to a specific city in India on Google Maps?

How can we restrict autosearch to only Pune city in India? I attempted the following: autocomplete.setComponentRestrictions( {'country': ['in']},{'city':['Pune']}); ...

What is the process for a webpage to save modifications made by JavaScript?

I am working on a simple web page with a form that contains checkboxes representing items from a database. When the submit button is clicked, these items may be retrieved. Additionally, there is an option to add a new item at the bottom of the page. My go ...

Can the lazy load script dependent on jQuery be utilized before the jquery.js script tag in the footer?

After receiving HTML from an AJAX callback, I noticed that there is a script tag for loading code that uses jQuery. However, I consistently encounter the error of jQuery being undefined. All scripts are connected before the closing </body> tag. Is ...

Toggle the visibility of a div based on the id found in JSON data

I am looking to implement a JavaScript snippet in my code that will show or hide a div based on the category ID returned by my JSON data. <div id="community-members-member-content-categories-container"> <div class="commun ...

What is the process of obtaining User properties through a URL and utilizing them as variables in JavaScript?

I need to retrieve the city properties: 918 using req.params.userMosque from the URL '/shalat/:userMosque'. I want to assign it to the variable city for customizing my API url request. However, it seems like it's not working as expected. I h ...

"Encountering issues with Rails and AJAX where the data returning is showing up

I am facing a challenge while trying to use AJAX in Rails to POST a comment without using remote: true. I am confused as to why my myJSON variable is showing up as undefined, while data is returning as expected. Check out my code below: function submitVi ...

Transferring information between Vue.js components via data emissions

Greetings from my VueJS Table component! <b-table class="table table-striped" id="my-table" :items="items" :per-page="perPage" :current-page="currentPage" :fields="fields" @row-clicked="test" lg >< ...

Custom Component in React Bootstrap with Overflowing Column

I am working on a custom toggle dropdown feature in my React application: import React from 'react'; import 'react-datepicker/dist/react-datepicker.css'; const DateRange = props => ( <div className="dropdown artesianDropdo ...

What is the best approach for deleting an element from an array based on its value

Is there a way to eliminate an element from a JavaScript array? Let's say we have an array: var arr = ['three', 'seven', 'eleven']; I want to be able to do the following: removeItem('seven', arr); I researc ...

Tips for effectively structuring material-ui Grid in rows

I am currently using the material-ui framework to create a form. Utilizing the Grid system, I want to achieve the following layout: <Grid container> <Grid item xs={4} /> <Grid item xs={4} /> <Grid item xs={4} /> </Gr ...

Transferring a uint8clampedarray Array to C# using JavaScript via ajax after extracting getImageData from the Canvas

Currently, I am facing an issue while attempting to create a signature using client-side javaScript and then forwarding the result to the back-end (c#) via ajax. The array I am trying to transmit is of the type uint8clampedarray, but unfortunately, the Set ...

The use of backticks within an HTML document for nesting purposes is not permitted

Currently, I am utilizing nodemailer to send HTML template code in Node.js. However, the issue I am encountering is that I cannot nest backticks within it: Here's my code snippet: let mailDetails={ from: 'example@example.com', to: & ...

Incorporating JSON data seamlessly into a visually appealing Highcharts pie chart

It seems like I'm facing a minor issue here. Everything was working fine until... $(document).ready(function() { // Original data var data = [{ "name": "Tokyo", "y": 3.0 }, { "name": "NewYork", "y": 2.0 }, { "name": "Berlin", ...