[Chartjs]-Chart.js- Dates not displaying correctly on chart and axis labels not showing

3👍

The problem here seems to be the lack of string delimiters around your dates.

The labels property without the delimiters ends up being something like this in your generated HTML.

labels: [2022-10-09, 2022-10-09, 2022-10-05, 2022-10-05, 2022-10-05],

JS processor, upon seeing 2022-10-09 assumes you want to calculate the result of subtracting 10 and 9 from 2022.

What you want to end up with is

labels: ['2022-10-09', '2022-10-09', '2022-10-05', '2022-10-05', '2022-10-05'],

and for that you have to change your labels iteration code to something like this (I’m not really familiar with Python or Django, but you get the idea 😉 )

labels: [{%for stat in date%}'{{stat}}',{%endfor%}],

0👍

Since your X axis contains dates, you should specify it in your options :

options: {
    scales: {
        x: {
            type : 'time', ...
        }
    }
}

Because X axis type is by default category, and for this to work, you should also include a time adapter like date-fns (more info here), and according to the docs :

The time scale requires both a date library and a corresponding adapter to be present.

That’s why I personally use date-fns because it’s all bundled in one file, and if you need date formatting (for labels and tooltips for example), here is the format page.

Leave a comment