Problem with Google Chart formatting

I currently have a Line chart displaying the Y axis as 20,000,000 and I would like to change the format to 20K. How can I modify the format in a Google chart? Any assistance is greatly appreciated. Code:

<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
          var data1=[["Year","sss","SSE"],["JAN",1234,7834],["FEB",0,0],["MAR",0,0],["APR",0,0],["MAY",0,0],["JUN",0,0],["JUL",0,0],["AUG",0,0],["SEP",0,0],["OCT",0,0],["NOV",0,0],["DEC",0,0]];

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

        var options = {
                  legend: {position: 'top',alignment:'center'},
                  vAxis: {viewWindow: {min:0},
               // ticks: [{v: 2000000000, f: '2k'}, {v: 2000000000, f: '4k'}, {v: 6000000000, f: '6k'}, {v: 8000000000, f: '8k'}, {v: 10000000000, f: '10k'},{v:12000000000,f: '12k'}],

                  title:'ROW & Returned($000)',
               // format:'#K',
             format:'$###,###',
                gridlines:  {color:'#e4e4e4', count: 7}},
                lineWidth: 4,
                colors: ['#69699f','#d53200','#69699f']
        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Answer №1

To format the axis, you will need to provide a list of locations and labels for tick marks using the vAxis.ticks option as scalar formats are not supported in the axis formatting options. There is a commented out line in your code that is meant to handle this task. Just uncomment it to make it work:

ticks: [{v: 2000000000, f: '2k'}, {v: 4000000000, f: '4k'}, {v: 6000000000, f: '6k'}, {v: 8000000000, f: '8k'}, {v: 10000000000, f: '10k'},{v:12000000000,f: '12k'}]

Answer №2

To dynamically generate ticks, you can use the following method based on the maximum value:

var maxValue = _getMaxValue;
options.ticks = _generateTicks(maxValue);

function _generateTicks(max) {
  var tickValues = [{v: 0}];    //first tick
  if (max > 0) {
    var exponent = Math.floor(Math.log(max) / Math.log(1000));
    max = Math.round(max / Math.pow(10000, exponent)) * Math.pow(10000, exponent);
    for (var tickIndex = 1; tickIndex < 5; tickIndex++){
      var value = max * tickIndex / 4;
      var formattedValue = (value / Math.pow(1000, exponent)).toFixed() * 1 + ' ' + [' ', 'k', 'M', 'G', 'T'][exponent];
      tickValues.push({v: value, f: formattedValue});
    }
  }
  return tickValues;
}

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

How can I switch out an item within FabricJS?

In order to incorporate undo and redo functionality, I have created an array named "history" that stores the most recent changes triggered by canvas.on() events. Displaying console.log: History: (3) […] ​ 0: Object { target: {…} } //initial object ...

Update the value in a nested object array by cross-referencing it with a second nested object array and inserting the object into the specified

I have a large array of objects with over 10,000 records. Each object contains an array in a specific key value, which needs to be iterated and compared with another array of objects. If there is a match, I want to replace that value with the corresponding ...

Switch up the picture when you press on it

I have a task involving a table where I want to switch out an image in the <td> when it is clicked, using a URL that I specify beforehand. The URL of the image will be provided when clicking on a link within the page. For example: index.html?type=d ...

What causes Firefox's CPU to spike to 100% when a slideshow begins that adjusts the width and left coordinates of certain divs?

Seeking Advice I'm in need of some help with identifying whether the code I'm working on is causing high CPU usage in Firefox or if it's a bug inherent to the browser itself. The situation is getting frustrating, and I've run out of so ...

Employ the v-model directive in conjunction with a checkbox in scenarios where v-for is implemented with the properties of an object

When utilizing v-model with a checkbox in conjunction with an array of objects, it functions correctly: new Vue({ el: '#example', data: { names: [ { name: 'jack', checked: true }, { name: 'john', checked ...

Is it possible to utilize the default error handling page rather than a specific view for expressing

Currently, I'm going through a tutorial on MDN Express for building a "Local Library" application that utilizes Pug (Jade) as its templating engine. In this segment of the tutorial, it explains the process of creating a controller to manage a form POS ...

The Johnny-Five stepper initiates movement within a for-loop

I am new to using node.js and johnny-five. I want to move a stepper motor 5 times with 1000 steps each. Here is what I have tried: do 1000 Steps in cw ; console.log('ready); do 1000 steps; console.log('ready') ... It woul ...

Looking to dynamically set a background image using data fetched from an API in a ReactJS project

Looking to incorporate a background image from an API response in ReactJS Here is some sample code: useEffect(() => { axios.get(`https://apiaddress=${API_KEY}`) .then(res=>{ console.log(res); setRetrieved(res.data); console.log(retrieved ...

Having trouble with JavaScript function returning false?

I am trying to call a JavaScript function on an ASP.NET button client click event and want to prevent postback. The function is working, but it is not preventing the page from posting back. Here is my JavaScript code: function User2Check() { v ...

AngularJS: Issue with JQuery Slider not Updating Scope Value

I am currently working on a project using AngularJS and I have integrated a jQuery slider into it. However, I am facing an issue where I need to change the value of a select box which is defined in a $scope array, but the functionality is not working as ex ...

javascript: verify the presence of uppercase and lowercase letters

Can the validation of at least 2 lowercase and 2 uppercase letters be implemented when checking the case? Below is the condition I am currently using. function HasMixedCase(passwd){ if(passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) return true ...

Utilizing Server-Sent Events to display a interactive navigation button

Currently, I am managing a web-based point of sale system where some buttons are hidden for specific functions. To streamline the process, I would like to allow managers to simply click on an "Enable" button in the admin panel and have it immediately refle ...

Encasing the window global variable within an AngularJS framework

Currently, I am encapsulating a global variable within a factory in order to make it injectable. Here is an example of how it's done: angular.module('Analytics').factory('woopra', [ '$window', function ($window) ...

MUI-Datatable rows that can be expanded

I'm attempting to implement nested tables where each row in the main table expands to display a sub-table with specific data when clicked. I've been following the official documentation, but so far without success. Below is a code snippet that I& ...

Using JavaScript, learn how to extract query parameters and encoded information from a URI

I am looking for a specific module in order to extract information from query parameters within a URL. The format includes 2 query parameters and an encoded piece of data. Do I need to use split functions or is there a more direct approach available? Sampl ...

"Encountered an error while trying to access properties that

Struggling to create a practice menu with the functionality of making elements appear and disappear on click? If you are encountering issues with a class named "option" not working as expected, you are not alone. Clicking on nested objects like images or i ...

JavaScript code that retrieves an array containing only the deleted images from the information obtained from the edit product page

Currently, I am working on an edit product page in react with a node backend. The situation is as follows: Initially, the product had 4 images (a.png, b.png, c.png, d.png). I have made updates by removing the a.png image and adding a new image e.png. So ...

What is the reason behind TypeScript choosing to define properties on the prototype rather than the object itself?

In TypeScript, I have a data object with a property defined like this: get name() { return this._hiddenName; } set name(value) { ...stuff... this._hiddenName = value; } However, when I look at the output code, I notice that the property is on ...

Can you create asynchronous code or functions without using Web APIs at all?

Even though JavaScript is single-threaded, I can't help but wonder about a function that takes an unusual amount of time without any involvement from web APIs like this: console.log("start") function banana() { let bananaCount = 10; while (b ...

Is there a way to completely define CSS animation using only JavaScript?

I am looking to implement CSS animation on HTML elements that are generated entirely through a JavaScript function. The approach I am taking involves customizing settings and functions for each part of the animation, which is why this method is necessary. ...