Error: Google chart for Google Maps is not displaying text every 1 unit as expected

I am looking to display all the hAxis labels in my chart. Due to the extensive length of the code exceeding 4000 lines, I will only include what I consider to be crucial:

var data = new google.visualization.DataTable();
data.addColumn('string', 'Sample');
data.addColumn('number', 'Elevation');
for (var i = 0; i < results.length; i++) {
  if(i%10==0)
  {
      data.addRow(['' + i / 10 + '', elevations[i].elevation]);
  }
  else
  {
      data.addRow([null, elevations[i].elevation]);
  }
}
document.getElementById('chart_div').style.display = 'block';
chart.draw(data, {
  height: 250,
  colors: ['#F00'],
  legend: 'none',
  titleY: 'Elevation (m)',
  titleX: 'Distance',
  hAxis: {
      slantedTextAngle: 90,
      showTextEvery: 1,
  }
});

The current outcome can be seen here: https://i.sstatic.net/Fq2kz.png

To achieve my desired result, I need the Distance of the hAxis to display numbers from 0 to 7 consecutively, with an appropriate font-size and angle.

Note: I prefer to have no title for every column except multiples of 10. Any solution that omits adding a title to those specific columns would also be acceptable!

Answer №1

Simply set hAxis.showTextEvery to 10.

To exclude the values of the first column from tooltips, utilize a tooltip-column.

If you choose the hAxis.slantedTextAngle option, also enable the hAxis.slantedText option with a value of true.

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

  function drawBasic() {
    //some sample data
    var elevations = [];
    for (var i = 0; i < 300; ++i) {
      elevations.push({
        elevation: 100 * Math.random()
      })
    }
    var results = elevations;
    
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Sample');
    data.addColumn('number', 'Elevation');
    data.addColumn({
      type: 'string',
      role: 'tooltip'
    });
    for (var i = 0; i < results.length; i++) {
      data.addRow([String(i / 10),
        elevations[i].elevation,
        String(elevations[i].elevation)
      ]);
    }

    document.getElementById('chart_div').style.display = 'block';
    var chart = new google.visualization.ColumnChart(
      document.getElementById('chart_div'));
    chart.draw(data, {
      colors: ['#F00'],
      legend: 'none',
      height: 250,
      titleY: 'Elevation (m)',
      titleX: 'Distance',
      
      hAxis: {
        slantedTextAngle: 90,
        slantedText: true,
        showTextEvery: 10,
      }
    });
  }
  
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
  <div id="chart_div"></div>

Answer №2

After experimenting with both ColumnChart and Bar from Google chart's options, it became clear that neither worked perfectly for all scenarios. Here is the solution that proved to be the most effective:

For loading the API:

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

When creating the LineCHart:

chart = new google.visualization.LineChart(document.getElementById('chart_div'));

And then specifying the options later in the code:

var options = {
  legend: { position: "none" },
  height: 250,
  colors: ['#F00'],
  hAxis: {
      title: 'Distance (<%= Event.DistanceUnits %>)',
      showTextEvery: 10
  },
  vAxis: {
      title: 'Altitude(m)'
  }
};

Lastly, when displaying the results, I included all of them in the visualization:

for (var i = 0; i < results.length; i++) {
    data.addRow(['' + i / 10 + '', Math.round(elevations[i].elevation)]);
}

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

Retrieve the array from the response instead of the object

I need to retrieve specific items from my database and then display them in a table. Below is the SQL query I am using: public async getAliasesListByDomain(req: Request, res: Response): Promise<void> { const { domain } = req.params; const a ...

How to pass the ng-repeat $index value as a parameter in AngularJS

Within the code snippet provided, there is a shell page index.html and a partial view currently utilized by two different controllers. The static data in AppController is connected to the list.html partial view and displayed as a table. In the JavaScript p ...

Custom styling options for Google Chart

I have been attempting to dynamically adjust the width and height of a google-chart directive by utilizing input field values. However, I am encountering an issue where the width and height are not updating as expected. Check out the Plunker here $scope. ...

Unable to transfer the properties of reactjs to react-chartist

How can I pass the state from the parent component "main.js" into the child component "bar.js"? //main.js import React, { Component } from 'react'; import BarChart from './Bar-chart'; class Hero extends Component { cons ...

The data type 'string | number | boolean' cannot be assigned to type 'undefined'. Specifically, the type 'string' is incompatible with type 'undefined'. Error code: ts(2322)

When attempting to create a partial object with specific fields from a full object that meet certain criteria, I encountered a TypeScript error message. To better explain this issue, I designed a test module to showcase the concept/problem without using ac ...

I am unable to get the radio button checked in Angular 2

I have set up a form with two radio buttons for gender selection, and I want to ensure that the previously selected option is displayed as checked. Here's the code snippet I've added in my template: <div class="form-group"> <label& ...

What is the best way to implement bypassSecurityTrustResourceUrl for all elements within an array?

My challenge is dealing with an array of Google Map Embed API URLs. As I iterate over each item, I need to bind them to the source of an iFrame. I have a solution in mind: constructor(private sanitizer: DomSanitizationService) { this.url = sanitizer. ...

Angular 2 Encounter Error When Trying to Access Undefined Property in a Function

Element: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-ore-table', templateUrl: './ore-table.component.html', styleUrls: [&a ...

Unveiling the Technique: Adjusting Field Visibility When Dropdown is Altered

I tried to find a solution on Stackoverflow for displaying/hiding a field based on dropdown selection using either jQuery or inline JavaScript. However, I am facing difficulties when implementing this within a table. Let's start with an easy approach ...

How many server queries does a single web application require?

As someone new to web app development, my main goal is to optimize speed as much as possible. I am faced with two options: The first option is to fetch data from the database individually every time a refresh is needed in the app. Alternatively, I c ...

Is there a way to execute a JavaScript function on a webpage using Selenium automation?

Here's an element on a website: <span class="log-out-ico" ng-click="logout()"> Instead of clicking it, I want to run the "logout()" script from selenium. Is that possible? If so, how can I do it? This is what I attempted: I ...

The ajax method for loading an xml file results in displaying the undefined message

When attempting to fetch content from an xml file using ajax, the page initially displays "undefined". However, upon refreshing the page, the content loads successfully. Take a look at my code snippet below: $.ajax({ type: "GET", url: "xm ...

Is it possible to access an external website by clicking on a link within a DIV element?

I have a basic website set up like this sample.php <html> <head></head> <body> <a id="myLink" href="http://sample.com">Click!</a> </body> </html> I displayed this website within a DIV-Container on a ...

Use ajax to add rows to the second-to-last table

I am facing a situation where I have a table with 25 default rows. When scrolling to the bottom of the table, I want to dynamically insert another set of 25 rows. Everything is functioning correctly, but in a specific scenario, I need to preserve the last ...

I am looking to update the appearance of a button dynamically in Vue.js based on changes to an

Is there a way to toggle a visible button when the array changes? I'm having trouble implementing this. What is the most effective method? Check out my example below: https://codesandbox.io/s/relaxed-poincare-vv6xh?file=/src/components/HelloWorld.vu ...

Guide to executing a server-side FUNCTION within a specific namespace room exclusively with the help of socket.io, express, and node.js

I've been developing an online multiplayer game using socket.io, express, and node.js. The server is supposed to detect the number of users connected to a specific room within a namespace and start the game if there are more than two players. However, ...

Is the Vis.js network function ready to go?

Utilizing the Vis.js network library to display graphs and am curious if there is a dedicated finishedLoading event available for this object? Any suggestions or insights are appreciated! ...

Having trouble displaying the Primevue dialog modal in Vue 3?

I am using [email protected] and [email protected] Main script import { createApp } from 'vue' import App from './App.vue' import router from './router' import PrimeVue from 'primevue/config'; import &apos ...

Update the content according to the size of the screen

I'm currently working on a project where I need to redirect pages based on screen sizes. I have separate index files for the mobile and web versions of the website. In the web version's index file, I've added the following script: <scri ...

Flask - Refreshing Forms Dynamically

In an effort to enhance the responsiveness of my app, I am looking for a way to prevent the page from reloading every time a POST request is sent. My current setup includes a dynamically generated form with input fields designed like this: <div class=&q ...