Use time in chart.js Angular
I would like to change my code so I can plot time vs bodyweight. Right now my typescript is:
parseOptions(Chart, chartOptions());
this.bodyweightChart = new Chart(
document.getElementById('bodyweightChart') as HTMLCanvasElement,
{
type: 'line',
data: {
labels: this.timelineLabel,
datasets: [
{
label: 'Bodyweight',
data: this.bodyweightData,
},
],
},
options: {
scales: {
yAxes: [
{
gridLines: {
color: '#e9ecef',
zeroLineColor: '#e9ecef',
},
ticks: {
min: Math.min.apply(this, this.bodyweightData) - 10,
max: Math.max.apply(this, this.bodyweightData) + 10,
},
},
],
},
},
}
);
Where bodyweightData
and timelineLabel
are arrays, and the chartOptions()
is as below:
export function chartOptions(): MyChartOptions {
// Options
const options: MyChartOptions = {
defaults: {
global: {
responsive: true,
maintainAspectRatio: false,
defaultFontColor: colors.gray[600],
defaultFontFamily: fonts.base,
defaultFontSize: 13,
layout: {
padding: 0,
},
legend: {
display: false,
position: 'bottom',
labels: {
usePointStyle: true,
padding: 16,
},
},
elements: {
point: {
radius: 0,
backgroundColor: colors.theme.primary,
},
line: {
tension: 0.4,
borderWidth: 4,
borderColor: colors.theme.primary,
backgroundColor: colors.transparent,
borderCapStyle: 'rounded',
},
},
tooltips: {
enabled: true,
mode: 'index',
intersect: false,
},
},
},
};
// y-axis
Chart.scaleService.updateScaleDefaults('linear', {
gridLines: {
borderDash: [2],
borderDashOffset: 2,
color: colors.gray[300],
drawBorder: false,
drawTicks: false,
lineWidth: 0,
zeroLineWidth: 0,
zeroLineColor: colors.gray[300],
zeroLineBorderDash: [2],
zeroLineBorderDashOffset: 2,
},
ticks: {
beginAtZero: true,
padding: 10,
callback: (value) => {
if (!(+value % 10)) {
return value;
} else {
return null;
}
},
},
});
// x-axis
Chart.scaleService.updateScaleDefaults('category', {
gridLines: {
drawBorder: false,
drawOnChartArea: false,
drawTicks: false,
},
ticks: {
padding: 20,
},
});
return options;
}
export const parseOptions = (parent: any, options: any) => {
for (const item in options) {
if (typeof options[item] !== 'object') {
parent[item] = options[item];
} else {
parseOptions(parent[item], options[item]);
}
}
};
On the documentation (https://www.chartjs.org/docs/latest/axes/cartesian/time.html), it states that I can pass an object as the data like so:
data: [{
x: new Date(),
y: 1
}, {
t: new Date(),
y: 10
}]
And do something like:
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
xAxes: [{
type: 'time',
distribution: 'series'
}]
}
}
});
How would I be able to achieve this and convert my code into something similar? Thank you very much! I’m very new to chart.js
Source: Angular Questions