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

Implement a React Component as a unique OverlayView within the Google Maps application

Utilizing the Google Maps JavaScript API V3, I have created a map with clustered and draggable map markers. Instead of relying on React libraries that interact with the google maps API, we chose to build our own solution due to limitations in drag function ...

"Flashes of canvas in constant motion between animated scenes

I have a practical exercise to do for school, but I am very new to HTML/JS. The issue I am facing is that my canvas is flashing, like it erases one image and then quickly displays another. I want both images to be displayed at the same time. Here is the co ...

Ensure that users must confirm their actions through a message prompt when attempting to exit the website

Looking to add a confirmation box that pops up when someone tries to leave my website. It's important to prevent any information from being lost if they accidentally navigate away. Can you provide detailed instructions on where exactly I should place ...

Is there a way to automatically scroll vertically to a specific line in HTML?

Trying to explain this is a bit tricky. I am looking to add an element to the HTML that prompts the browser to scroll vertically to its location automatically when loaded, similar to an anchor. So: | visible area | | content html | | content html | ...

Tips for switching out images depending on the time of day

Currently, I have a script that dynamically changes the background color of my webpage based on the time of day. However, I am facing issues trying to implement a similar functionality for replacing an image source. The current code is also time zone-based ...

How can one properly utilize material-ui CSS?

Just starting out with material-ui and react, I'm currently following this palette customization guide from Material-UI. However, when attempting to replicate the example shown, I encountered the error: Cannot read property 'prepareStyles' ...

A Step-by-Step Guide to Clearing JSON Cache

I'm currently utilizing jQuery to read a JSON file. However, I've encountered an issue where the old values are still being retrieved by the .get() function even after updating the file. As I continuously write and read from this file every secon ...

how to prevent autoscrolling in an angular application when overflow-x is set to

In my socket event, I am using $scope.items.unshift(item) to place the new item at the top of the list. The html code includes <ol ng-repeat="item in items"><li>{{item.name}}</li></ol> An issue arises when a new item is added whil ...

Troubleshooting: Issue with AngularJS Image onload directive - "this" reference not functioning properly?

I have a custom directive that looks like this: .directive('ngImageOnLoad', function () { return { restrict: 'A', link: function(scope, element, attrs) { element.bind('load', function() { ...

One Functionality on Button is Failing to Execute among Several Tasks

I've encountered an issue with one of the tasks triggered by a button click. The button successfully executes two out of three tasks (hides them on click), except for the last task which involves a text-blinking JavaScript function. I've used the ...

Struggling with updating state using splice method within an onClick event in React Hooks

CODE DEMO I'm facing an issue with my code snippet where it appears fine when I console.log it, but fails to set the state. The goal is to delete a box by using splice when clicked, however, something seems to be preventing it from working properly. ...

Ways to reload the page following the submission of a form

I implemented a fade dialog to present a form, and successfully submitted the form using ajax to create a new record in the database. Now, I am facing an issue where I cannot refresh the page after the ajax call finishes. Despite attempting to use JavaScr ...

Retrieve content from JSON post data

I have been facing an issue where I am trying to send a JSON file from a web page to a nodeJS server. My goal is to assign the JSON file to an object on the server side and print it out in the console. Despite researching extensively online and attempting ...

Angular: Maximizing Input and Output

I'm having trouble with the function displaying within the input field. My goal is to simply allow the user to enter a name and have it displayed back to them. HTML: <div ng-app = "mainApp" ng-controller = "studentController"> <tr> < ...

Ensure that the jQuery Knob is set to submit any modifications only after the final adjustment

Utilizing jQuery Knob by anthonyterrien, I have configured the step to be 20. My goal is to transmit the knob's value to the server. The issue arises when the change function is triggered every time the user adjusts the knob using either a right or le ...

The error message "Unable to push property in an undefined array" is displayed when attempting to push a property into

I'm struggling to debug the error message TypeError: Cannot read property 'push' of undefined. The following code snippet is what's causing the problem: const parent_lead_contact = this.props.parentLeads?.filter((lead) => lead. ...

Setting up only two input fields side by side in an Angular Form

I'm fairly new to Angular development and currently working on creating a registration form. I need the form to have two columns in a row, with fields like Firstname and Lastname in one row, followed by Phone, Email, Password, and Confirm Password in ...

Enhancing a popup with animated effects

I have been working on a popup that I want to add a subtle animation to. A fade effect seems like the perfect solution. Here is the code for the button: <a href="javascript:void(0)" onclick="document.getElementById('back_overlay').style.disp ...

Using the ng-repeat directive along with the string replace expression allows for dynamically

Struggling to find a way to remove a substring within an angular expression while using the ng-repeat directive. The controller resides in an external JavaScript file, and here is the corresponding HTML code snippet. function myController($scope, $http ...

ng-if not functioning properly following the activation of the "Save Changes" button

When I click the edit change button, I am updating information and then hiding the form to show the updated details by clicking on the Save Changes button. My API successfully updates the information, but for some reason, ng-if does not seem to work afte ...