ChartJS v3 custom displayFormats

164 Views Asked by At

I'm trying to add a string (Week) next to the week number in xAxes in Chartjs 3. But it shows a random number instead of the string.

Here is the part of my code in the options:

scales: {
            x: {
                    type: 'time',
                    time: {
                        unit: 'week',
                        displayFormats: {
                            week: "'Week' W",
                        },
                        tooltipFormat: 'YYYY-W',
                    },
                    ticks: {
                        source: 'data',
                    },
                    offset: true,                   
                },  
              .........

Current output: '51124' 10

Expected output: Week 10

any help would be appreciated. Thanks

1

There are 1 best solutions below

1
On

"'Week' W" is a formating string, depending on which adapter you are using 'Week' will be translated to a specific value.

You could check if your adapter support custom strings in the format-string,...
Or you try to modify the label with a callback, like shown here in the documentation: https://www.chartjs.org/docs/latest/axes/labelling.html

Here the relevat code, adapted to fit your code snippet:

...
scales: {
     x: {
         type: 'time',
         time: {
             unit: 'week',
             displayFormats: {
                 week: 'W',
             }
         },
         ticks: {
             // This prepends the "Week" before the label
             callback: function(value, index, ticks) {
                 return '"Week" ' + value;
             }
         }
     }
 }
 ...