I have a data from the backend(flask-sqlalchemy with mysql) in which data contains date in integer for week, month and year that looks like this:
in this case the x represents the week of the year:
let month_true = [
{
bob: {
"base-certificate": 60,
"case-certificate": 1,
"standard-certificate": 7,
},
x: 9,
},
{
bob: {
"base-certificate": 30,
"case-certificate": 4,
"standard-certificate": 5,
},
x: 11,
},
];
The first thing I did was to map the data and change the x into a readable format for Javascript and chart.js, using a function that converts week of the year number to actual date:
the function:
function getDateOfWeek(w, y) {
var d = 1 + (w - 1) * 7; // 1st of January + 7 days for each week
return new Date(y, 0, d);
}
Mapping through the data:
let newData = month_true.map(function (m) {
let dateObject = new Date();
let year = dateObject.getFullYear();
const weekDate = getDateOfWeek(m.x, year);
let r = new Date(Date.parse(weekDate));
const newd = {
x: r.setHours(0, 0, 0, 0),
base: m.bob["base-certificate"],
case: m.bob["case-certificate"],
standard: m.bob["standard-certificate"],
};
return newd;
});
let newdate = newData.map(function (d) {
return d.x;
});
now construct the chart:
let ctx = document.getElementById("chart").getContext("2d");
let config = {
//labels: newdate,
type: "bar",
data: {
datasets: [
{
label: "base",
data: newData,
parsing: {
xAxisKey: "x",
yAxisKey: "base",
},
},
{
label: "Case",
data: newData,
parsing: {
xAxisKey: "x",
yAxisKey: "case",
},
},
{
label: "Standard",
data: newData,
parsing: {
xAxisKey: "x",
yAxisKey: "standard",
},
},
],
},
options: {
scales: {
x: {
ticks: {
beginAtZero: true,
},
offset: true,
type: "time",
time: {
//isoWeekday: true,
unit: "week",
},
},
},
},
};
let myChart = new Chart(ctx, config);
It got plotted but the x-axis is not showing the second label:
what can I can do tomake the labels appear completely?
This is because by default the time scale auto generates ticks, if you dont want to include the labels from your data you need to set ticks.source to data:
options: {
scales: {
x: {
type: 'time',
ticks: {
source: 'data'
}
}
}
}