javascriptchartsgoogle-apigoogle-visualizationcolumn-chart

how to change the range of xaxis of google column chart?


I am using google column chart to create a column chart as shown below:

const chart = new google.visualization.ColumnChart(chartDiv); // Extract the data from which to populate the chart.

        chart.draw(data, {
          height: 300,
          legend: "none",
          // @ts-ignore TODO(jpoehnelt) check versions
            titleY: "Elevation (Meters)",
            titleX: "Distance (Miles)"

        });

The one problem is the values in xaxis. How can i only show 5 values for eg. 1, 2, 3, 4, 5? The xaxes values that are marked in red is populated densely. How to divide into 5 sections? Thanks for the help!

enter image description here


Solution

  • see the config options for --> hAxis

    there are a number of options to control the labels on the axis.

    to divide the axis into segments,
    use the gridlines.count option.

    this allows you to specify how many gridlines will be displayed,
    and thus the number of labels.

    hAxis: {
      gridlines: {
        count: 5
      }
    },
    

    see following working snippet...

    google.charts.load('current', {
      packages:['corechart']
    }).then(function () {
      var data = new google.visualization.DataTable();
      data.addColumn('number', 'x');
      data.addColumn('number', 'y');
    
      var y = 1380;
      for (var i = 0; i <= 500; i++) {
        data.addRow([i, (i % 2 === 0) ? y + i : y - i]);
      }
    
      var options = {
        chartArea: {
          left: 64,
          top: 48,
          right: 32,
          bottom: 64,
          height: '100%',
          width: '100%'
        },
        hAxis: {
          gridlines: {
            count: 5
          },
          slantedText: true,
          slantedTextAngle: 45
        },
        height: '100%',
        legend: {
          alignment: 'start',
          position: 'top'
        },
        width: '100%'
      };
    
      var chart = new google.visualization.ColumnChart(document.getElementById('chart'));
      chart.draw(data, options);
    });
    html, body {
      height: 100%;
      margin: 0px 0px 0px 0px;
      overflow: hidden;
      padding: 0px 0px 0px 0px;
    }
    
    #chart {
      height: 100%;
    }
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="chart"></div>