chartjs / Chart.js

Simple HTML5 Charts using the <canvas> tag
https://www.chartjs.org/
MIT License
63.92k stars 11.89k forks source link

Ticks callback function don't return initial value labels #11748

Closed ClineResearch closed 2 months ago

ClineResearch commented 2 months ago

Expected behavior

Hi! We want to display every 2 labels on the abscissa axis. These labels are character strings. If we apply this callback function: function (value, index, values) { return index % 2 === 0 ? value : '' } the labels returned are integers corresponding to the indexes of the values. The result should be the initial character string. How to fix this problem? Thanks for your responses.

Current behavior

The value labels returned are integers corresponding to the indexes of the values. The result should be the initial character string.

Reproducible sample

https://codepen.io/Jean-Fran-ois-Ramadier/pen/bGJQNxz

Optional extra steps/info to reproduce

No response

Possible solution

No response

Context

No response

chart.js version

v4.4.2

Browser name and version

No response

Link to your project

No response

LeeLenaleee commented 2 months ago

This is working as designed. You need to call this.getLabelForValue(value) as described in the docs here

The [category axis](https://www.chartjs.org/docs/4.4.0/axes/cartesian/category), which is the default x-axis for line and bar charts, uses the index as internal data format. For accessing the label, use this.getLabelForValue(value). [API: getLabelForValue](https://www.chartjs.org/docs/4.4.0/api/classes/Scale.html#getlabelforvalue)

Changing your tick callback to this will give the desired result:

callback: function (value, index, values) {
    return index % 2 === 0 ? this.getLabelForValue(value) : '' // Affiche une étiquette sur deux
},
ClineResearch commented 2 months ago

Thank you so much! Sorry, i should have read the docs better. Have a nice day! JF