1👍
✅
Simple example of using time on x axis. Don’t forget the luxon, chartjs-adapter-luxon libraries, order is important.
// '+new Date('2022-01')' return time in milliseconds 1640995200000
const exampleData = [{
"x": +new Date('2022-01'),
"y": 1000
},
{
"x": +new Date('2022-02'),
"y": 11000
},
{
"x": +new Date('2022-05'),
"y": 5000
},
{
"x": +new Date('2022-06'),
"y": 5500
},
{
"x": +new Date('2022-07'),
"y": 7000
},
{
"x": +new Date('2022-08'),
"y": 7000
},
{
"x": +new Date('2022-09'),
"y": 7000
},
]
const chartCfg = {
type: 'line',
data: {
datasets: [{
borderColor: 'green',
backgroundColor: 'green',
borderWidth: 1,
pointStyle: 'cross',
data: exampleData,
label: 'example',
}],
},
options: {
maintainAspectRatio: false,
animation: false,
scales: {
x: {
type: 'time',
time: {
displayFormats: {
month: 'yyyy-MM',
},
},
},
},
},
};
const chartCtx = document.getElementById('chart').getContext('2d');
const chart = new Chart(chartCtx, chartCfg);
chart.canvas.parentNode.style.width = '400px';
chart.canvas.parentNode.style.height = '300px';
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.4.0/luxon.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-adapter-luxon/1.1.0/chartjs-adapter-luxon.min.js"></script>
<canvas id="chart""></canvas>
Source:stackexchange.com