2👍
✅
First, you should define the xAxis
as a time cartesian axis. Then you define the data
of your dataset as individual points through objects containing x
and y
properties.
Please note that Chart.js internally uses Moment.js for the functionality of the time axis. Therefore you should use the bundled version of Chart.js that includes Moment.js in a single file.
new Chart(document.getElementById("myChart"), {
type: "line",
data: {
datasets: [{
label: "Unemployments",
data: [
{ x: '2020-01', y: 50 },
{ x: '2020-02', y: 55 },
{ x: '2020-03', y: 67 },
{ x: '2020-04', y: 40 },
{ x: '2020-05', y: 20 },
{ x: '2020-07', y: 35 },
{ x: '2020-08', y: 38 },
{ x: '2020-09', y: 45 },
{ x: '2020-10', y: 48 },
{ x: '2020-11', y: 52 },
{ x: '2020-12', y: 55 }
],
backgroundColor: 'lightblue',
borderColor: 'blue',
pointRadius: 5,
pointHoverRadius: 10,
fill: false,
}]
},
options: {
responsive: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
type: 'time',
time: {
unit: 'month',
parser: 'YYYY-MM',
displayFormats: {
month: 'MMMM'
},
tooltipFormat: 'MMMM'
}
}]
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>
Source:stackexchange.com