I'm currently facing an issue with labeling the axes on my chart using chart.js v3.9.1. Despite following the documentation, the labels are not appearing as expected (see image here: https://i.sstatic.net/wCod7.png
health_hub_tracker.html:
{% extends 'base.html' %}
{% load static %}
{% block content %}
<h1>Weight Tracker</h1>
<canvas id="myChart" width="400" height="200"></canvas>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [{%for stat in date%}{{stat}},{%endfor%}],
datasets: [{
label: 'Weight (lbs)',
data: [{%for stat in weight%}{{stat}},{%endfor%}],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
x: {
title: {
display: true,
Text: 'Date'
}
},
y: {
beginAtZero: true,
title: {
display: true,
Text: 'Weight (lbs)'
}
}
}
}
});
</script>
{% endblock content %}
views.py:
def health_hub_tracker(request):
serialized_weight = []
serialized_date = []
for stats in HealthStats.objects.filter(user=request.user):
serialized_weight.append(int(
stats.weight,
))
date_only = stats.date.date()
serialized_date.append(str(
date_only
))
print(serialized_weight)
print(serialized_date)
context = {
"weight": serialized_weight,
"date": serialized_date
}
return render(request, "health_hub_tracker.html", context)
On the x axis of the chart, the dates seem to be added up rather than displayed individually.
The list of data I have is: ['2022-10-09', '2022-10-09', '2022-10-05', '2022-10-05', '2022-10-05']
It appears that the dates are being calculated instead of being shown as strings. Any suggestions on how to rectify this issue?
Your assistance would be greatly appreciated!