Skip decimal points on y-axis in chartJS
Asked Answered
I

11

96

I am using this library to draw charts in my web app. The issue is that I am having decimal points in my y-axis. You can see that in the image below enter image description here

Is there a way that I can restrict it to only have numbers?

This is my code

var matches = $("#matches").get(0).getContext("2d");

var data = {
        labels: labelsFromCurrentDateTillLastWeek,
        datasets: [
            {
                label: "Last Weeks Matches",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: result
            }
        ]
    };

    var options = {
        scaleLabel: function (label) {
            return Math.round(label.value);
        }
    };

    var myLineChart = new Chart(matches, {
        type: 'bar',
        data: data,
        options: options

    })
Inez answered 8/6, 2016 at 10:8 Comment(0)
T
148

Update: please see an updated answer from @DreamTeK that shows how this can now be done as part of the chartjs api https://mcmap.net/q/217657/-skip-decimal-points-on-y-axis-in-chartjs


in chartjs 2.x you can pass an option for a userCallback to the yaxis tick field. In this you can check if the label is a whole number

here is an example

 options = {
     scales: {
         yAxes: [{
             ticks: {
                 beginAtZero: true,
                 userCallback: function(label, index, labels) {
                     // when the floored value is the same as the value we have a whole number
                     if (Math.floor(label) === label) {
                         return label;
                     }

                 },
             }
         }],
     },
 }

fiddle example

Thumb answered 8/6, 2016 at 12:23 Comment(5)
Is there a COMPLETE document guide for these charts? This chartjs.org/docs/latest/charts/line.html is detailed but says nothing about beginAtZero for example.Harkness
The best solution. No bug, no problemDaff
Easier option: chartjs.org/docs/latest/axes/radial/…Seritaserjeant
@Seritaserjeant the issue with that is all your charts will then use that stepSize. this is fine if you know you are always displaying data between 1 and 5 but if you are displaying data between 1 and 1000 it will still use the same step sizeThumb
This should be a simple flag. IMHO this is a very general use case and should be implemented like that.Manuel
H
111

2019 Update

This can now easily be achieved using the precision option:

ticks: {
  precision:0
}

As per the documentation.

If defined and stepSize is not specified, the step size will be rounded to this many decimal places.

EXAMPLE

options: {
  scale: {
    ticks: {
      precision: 0
    }
  }
}

OR (Single Axis)

options: {
  scales: {
    xAxes: [{
      ticks: {
        precision: 0
      }
    }]
  }
}
Hailee answered 2/1, 2019 at 12:33 Comment(5)
For others, note that this property doesn't seem to affect the labels when the user hovers/taps on a point in the graph...Asuncionasunder
Where should you put ticks?Venice
@Venice It's in options/scale/ticks. There's a link to the official documentation and example in my post.Hailee
Does not seem to work in version 3 any moreCudweed
Not working for chartjs-plugin-zoom 1.2.0 and chart.js 3.7.0 when zooming.Ornery
A
33

Update: replaced references to 'fixedStepSize' with 'stepSize'.

Another alternative is to use the stepSize option as follows:

options = {
    scales: {
        yAxes: [{
            ticks: {
                stepSize: 1
            }
        }],
    },
};
Aorta answered 23/2, 2017 at 21:39 Comment(3)
This should be that simple. Unfortunately, this setting prevents skipping certain points when there is a lot of data. For example, when the values are from 0 to 1000, chart.js will display all integers from 0 to 1000 instead of displaying e.g. 0, 100, 200 etc.Palingenesis
Good to know. So in essence, it works where the range of values is limited to what can be displayed reasonably within the available space.Aorta
Currently using 2.7 and 'fixedStepSize' should be 'stepSize' see docs: chartjs.org/docs/latest/axes/radial/…. Also does not play well if applying currency formatting.Seritaserjeant
D
23

You can adding stepSize and beginAtZero option like this:

scales: {
  yAxes: [{
    ticks: {
      stepSize: 1,
      beginAtZero: true,
    },
  }],
},
Doehne answered 23/1, 2020 at 9:47 Comment(2)
For Chart.js 2.9.4, stepSize works. thanks!!Porett
Please do not use the words "latest version" on this site.Meteoroid
G
4

The easiest and most straight forward solution is to add these configurations to your options object:

    scales: {
  yAxes: [
    {
      ticks: {
        precision: 0,
        beginAtZero: true,
      },
    },
  ],
},

and define the Axes (In my case it is the yAxes) depending on your axes with fractions

Ganges answered 29/3, 2021 at 12:30 Comment(0)
T
4

if you are using chart.js version 3.9.1 or higher , yAxes and xAxes will not work, also you may get this error in your console

Invalid scale configuration for scale: yAxes

for solving this problem you should use y instead of yAxes and x instead of xAxes .

example:

scales: {
        y: {
          suggestedMin: 0,
          ticks: {
            precision: 0
          }
        }
      }
Tegular answered 2/9, 2022 at 12:54 Comment(0)
J
3

I use this:

yAxes: [
        {
            ticks: {
                    callback: function(val) {
                    return Number.isInteger(val) ? val : null;
                }
            }
        }
    ]

Note: use the callback function for better granular control. We check if val is an integer instead of a floating-point decimal. If it is, we return the value. If not, we return null.

Jaquez answered 4/12, 2020 at 15:27 Comment(0)
T
2

Chart.js v3 (2022+)

The most reliable way with Chart.js v3 is not to use ticks.precision, but instead provide your own formatter with ticks.callback.

Example on how to format y axis labels:

scales: {
  y: {
    ticks: {
      callback: (yValue) => {
        return Math.floor(yValue); // format to your liking
      },
    },
  },
}

Documentation: https://www.chartjs.org/docs/latest/samples/scale-options/ticks.html

Tailored answered 30/4, 2022 at 12:10 Comment(0)
I
1

You can yaxis optopn;

decimalsInFloat: Number

Number of fractions to display when there are floating values in y-axis. Note: If you have defined a custom formatter function in yaxis.labels.formatter, this won’t have any effect.

Intertype answered 19/11, 2020 at 12:20 Comment(0)
D
0

if your chartjs version above 2.8 you can easily use precision: 0

study the below example

      responsive: true,
      maintainAspectRatio: false,
      title: {
        display: true,
        position: 'top',
        text: 'Monthly Establish Documents Value',
        fontSize: 25
      },
      scales: {
        xAxes: [
          {
            stacked: true,
            scaleLabel: {
              display: true,
              labelString: 'Months'
            }
          }
        ],

        yAxes: [
          {
            stacked: true,
            beginAtZero: true,
            id: 'A',
            scaleLabel: {
              display: true,
              labelString: '$AUD'
            }
          },
          {
            stacked: false,
            beginAtZero: true,
            id: 'B',
            gridLines: {
              display: false
            },
            scaleLabel: {
              display: true,
              labelString: '#Clients '
            },
            position: 'right',
            ticks: {
              min: 0,
              precision: 0
            }
          }
        ]
      }
    } ```
Dysprosium answered 7/12, 2021 at 7:41 Comment(0)
N
0

I had issues with all the examples above. Ended up having to use a callback. I'm using this in Typescript ReactJS FYI.cardSettings.precision contains the precision. This is a snippet from my code

 const [chartOptions, setChartOptions] = useState<ChartOptions<'line'>>({
    responsive: true,
    plugins: { 
    },
    scales: { 
        y: {
            display: true,
            ticks: {
                callback: function (value, index, values) { 
                    return parseFloat(value.toString()).toFixed(cardSettings.precision);
                }
            }
        }
    }
});
Nerti answered 27/2 at 5:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.