How to show only integers (no decimals) in chart API x/y-axis labels
Asked Answered
D

11

28

I'm using a column chart with the Google Chart JS Api. I'm displaying some values (total orders by day) that can only be represented as integers.

Everything is working great, except that when one of the charts I'm displaying has values that are too low, like 1 or 2, it starts to show decimals on the y-axis. The decimals look silly b/c it's impossible to have "half" an order (which is what I'm counting), and I'd like to hide this if possible.

Dissepiment answered 19/8, 2011 at 16:34 Comment(5)
I'm not familiar with the Google chart API, but can you apply parseInt(val) to the numbers before you display them?Metcalf
I'm not sure I know what you mean, I'm already supplying them as ints when the page is rendered. The decimals only appear when the number represented is very small, like 1 or 2.Dissepiment
Sounds like a floating-point error of some kind, then. If so, parseInt(val) is the correct approach to eliminate them. That's the best advice I can give without a specific instance to look at.Metcalf
Did you ever figure this out? I've got the same problem.Budde
you should be able to provide decimals as 'number of orders' anyway - in the case of 'average number of orders' - but display as intsAeniah
L
35

use the option

vAxis: {format: '0'}

as in

chart.draw(data, {
                   width: 800,
                   height: 480,
                   orientation: 'horizontal',
                   vAxis: {format: '0'}
                  }
           );
Lure answered 2/4, 2014 at 8:12 Comment(3)
It work for the text but the line is not to draw lines.The line is drawing at 2,5 with label 2Yalta
It does not work correctly, I have 2 lines with label (1) now.Trashy
I've found this doesn't work when you are dealing with low values. With a maximum value of 2, bu y axis displayed 0, 1, 1, 2, 2Baroda
S
29

I don't have enough rep to reply to Ian Hunter's post directly, but what that does is format the label, but doesn't set the grid lines to the same value as the label, which can have undesirable results. So let's say you have these grid lines:

10

7.5

5

2.5

0

When you format the label to only show integers it shows this: 10 8 5 3 0

But then your data on the graph doesn't tie-in with the y-scale labels. E.g If you have a value of 3 it actually shows above the '3' labels because the '3' label is actually 2.5

Unfortunately, the only solution I could think of was to monitor the min/max ranges of the data shown in the graph, and then apply some logic to set the min/max according to how many y-scale labels I have, such that they would divide with no remainders.

So in the case above, I'd set it to

        vAxis: { 
          viewWindow:{
            max:12,
            min:0
          }
        }

This would give grid lines of

12

8

6

4

0

No decimals, and no problems with the data not correlating with the labels on the graph.

Stallings answered 16/4, 2013 at 12:10 Comment(0)
P
13

Adding {format : 0} converts the float ticks to integers but the actual values on the bars appear incorrectly.

The main issue is Google Charts API assumes you want 5 gridlines mostly which may not work out to give you integer tick values.

Adding this gave me nice round tick values -

  gridlines: { count: -1}

source - https://groups.google.com/forum/#!topic/google-visualization-api/4qCeUgE-OmU

Pasquil answered 17/3, 2015 at 7:1 Comment(3)
This is most relevant answerGielgud
no, this one creates negative values on my vertical axis, and I don't want it.Trashy
@YevgeniyAfanasyev this may be a bit too late, but if you add minValue: 0 to the axis options, it should prevent negatives from happening.Pagination
T
4

if you want only the integer values to be shown, you should take to account that google charts wants to show you at least 5 gridlines. Presuming all of them should be integer give the graph following:

vAxis: {  title: 'Orders Count',

                minValue: 4,                    
                viewWindow:{min:0}, /*this also makes 0 = min value*/         
                format: '0',                     
            },
Trashy answered 26/10, 2015 at 4:44 Comment(0)
F
1

The easiest way is to edit the left vertical axis, with Min as 0, and Max as a multiple of 5 (5, 10, 15 etc) as appropriate to your expected maximum.

Frissell answered 5/1, 2017 at 15:35 Comment(0)
M
1

This issue will be resolved if you use vAxis: {gridlines: { count: 4}}

Meridithmeriel answered 24/9, 2019 at 14:49 Comment(0)
R
0

In my case I have values ranging from 0 to 600.

  • if $value is smaller than 12: use the max value for vAxis.gridlines.count
  • if $value is greater than 12: use the default nr of gridlines (4)

In this way you only display 'whole numbers'.

You'll need to dynamically generate the javascript off course.

Code Example:

google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
    var data = google.visualization.arrayToDataTable([
        ['Fase', 'Closed', 'Open'],
        <?php
        $max = 0; // needed to determine the number of gridlines?
        $data = array();
        foreach($projectExecutions as $key => $pe){
            $totals = countOpenIssuesInProjectExecution($pe);
            $open = $totals['open'];
            $closed = $totals['closed'];
            $data[] = "['". $FASE[$pe['fase_id']] . "', " . $closed . ", ". $open . "]\r\n";
            // What are the Max values vor Open & Closed Defects
            if($open > $max ){ $max = $open; }
            if($closed > $max ){ $max = $closed; }
        }
        $nrOfGridLines = ($max >= 12 ? 4 : $max+1); // Calculate the number of gridlines
        echo implode(",",$data);
        ?>
    ]);
    var options = {
        legend: { position: 'bottom' }
        ,title: "Evolution Defects: Open -VS- Closed"
        ,colors:['#00a160','red']
        ,isStacked: true
        ,vAxis: {textPosition: 'in', minValue:0,viewWindow: { min: 0 }, gridlines: {count: <?php echo $nrOfGridLines; ?>} }

    };
    var chart = new google.visualization.AreaChart(document.getElementById('chart_defects'));
    chart.draw(data, options);
}
Roede answered 25/7, 2017 at 9:41 Comment(0)
P
0

I'm using the following code:

google.charts.setOnLoadCallback(function(){
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Y');
    data.addColumn('number', 'X');

    var max = 0; //Or something like Int.MinValue
    for (var i = 0;i< arr.length;i++) {
      max = (arr[i]>max)? arr[i]:max; //calculate max value
      data.addRow("<<some calculation>>");
    }

    var options = {
      height: 300,
      vAxis: {
        gridlines: { count: max+1}, //+1 is importent for the origingridline
        viewWindow:{
          min: 0,
          max: max
        },
      }
    };

    var chart = new google.visualization.ColumnChart(document.getElementById("<< div_id >>"));

    chart.draw(data, options);
  }

Just calculate your maximum value and then set gridlines.count to this value

Politick answered 29/8, 2017 at 15:42 Comment(0)
S
0

I'm using the Guava Multiset as my data. Cagy79's trick is the only one that I was able to get working. I also tried generating my own lines using an IntStream, but still had fractional numbers for some of the graphs. As mentioned above, just setting the format will create a graph where the hover over value and the gridline differ.

Multiset items = TreeMultiset.create();

Items added using .add and .addAll

Make sure the items are sorted:

occurrences = Multisets.copyHighestCountFirst(items);

String option = "hAxis : { title : 'Count', gridlines : { count:" + ((max >=12) ? 4 : max+1) + } }")

Spotty answered 6/5, 2018 at 21:48 Comment(0)
A
0

I prefer the gridlines: { count: -1 } option, but you can always explicitly specify the values you want with ticks. Cool thing about this is they don't even have to be evenly spaced - you could do [1, 10, 100, 200, 500, 1000] if you wanted:

options: { vAxis: { ticks: [1,2,3,4,5,6,7,8,9,10] } }

Depending upon your data you may want to hardcode this or use thresholds.

Aeniah answered 1/11, 2018 at 20:7 Comment(1)
This doesn't seem to work with histogramsEddie
L
0

For anyone that are also searching for the answer, you can see the answer to this question here, which use options format. Can't get Google Charts Axis to format in decimal

Labelle answered 2/1, 2019 at 1:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.