Search code examples
google-apps-scriptchartsgoogle-visualization

Google Charts column chart how to change vertical axis scale?


I have a column chart which I am trying to set the vertical axis scale to whole numbers i.e. 0, 1, 2... instead of 0, 0.5, 1...

Using vAxis : {format : '#'} merely rounds up the decimals, leaving duplicates i.e. 0, 1, 1, 2, 2...

Using vAxis : { gridlines : { count : 5 // for example } } does not seem to have an effect.

Ticks look like a solution but my question is what if my chart is to be dynamic? If I don't know what the max number of jobs would be, so as to set the ticks?

The last resort seems to be putting a height constraint on the chart, forcing the v-axis unit to be larger.

Thank you in advance!


Solution

  • to use ticks and still be dynamic,
    you can use data table method getComumnRange(columnIndex)
    to determine the min and max values of the y-axis values

    then use those values to build the ticks array,
    see following working snippet...

    google.charts.load('current', {
      packages:['corechart']
    }).then(function () {
      var data = google.visualization.arrayToDataTable([
        ['category', 'value'],
        ['a', 1],
        ['b', 10],
        ['c', 4],
        ['d', 3],
        ['e', 7]
      ]);
    
      var yAxisRange = data.getColumnRange(1);
      var ticks = [];
      for (var i = 0; i <= yAxisRange.max; i++) {
        ticks.push(i);
      }
    
      var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
      chart.draw(data, {
        vAxis: {
          format: '0',
          ticks: ticks
        }
      });
    });
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="chart_div"></div>