[Chartjs]-Chart.js xaxis formatter changes the value shown in the chart

2๐Ÿ‘

โœ…

As per the tip in the docs:

The category axis, 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

so to get the right display value your callback needs to be this:

ticks: {
    callback: function(value, index, ticks) {
        return `${this.getLabelForValue(value)}:00`;
    }
}

1๐Ÿ‘

You can edit the labels, but in my opinion a better solution would be to implement a Time cartesian axis. This would allow you to add more data without making changes to the labels. You would need to include a time adapter to make it work.

config:

const config = {
  type: 'line',
  data: data,
  options: { 
      scales: {
          xAxis: {
                type: 'time',
                
                ticks: {
                    source: 'labels', // get ticks from given labels
                },

                time: {
                    minUnit: 'minute', // smallest time format

                    displayFormats: {
                        minute: "HH:mm",
                        hour: "dd/MM HH:mm",
                        day: "dd/MM",
                        week: "dd/MM",
                        month: "MMMM yyyy",
                        quarter: 'MMMM yyyy',
                        year: "yyyy",
                    }
                }
            },
        },
    }
};

Here is a fiddle to show you how this would look: JSFiddle

Leave a comment