let yourDataJson = [{x: '2021-08-13', y: 20.2},{x: '2021-08-15', y: 16},{x: '2021-08-19', y: 9},{x: '2021-08-23', y: 35},{x: '2021-09-02', y: 2}];
let yourData = {
datasets: [{
label: 'Orders: Product A',
data: yourDataJson,
borderColor: 'rgba(0,0,255,1)',
backgroundColor: 'rgba(0,0,255,0.5)',
fill: true
}
]
};
let yourOptions = {
scales: {
x: { // <-- v3.x now object "{", not array "[{" anymore
type: 'timeseries', // <-- try "time" and "timeseries" to see difference
time: {
unit: 'day', // <-- set 'hour' / 'day' / 'week' / 'month' or 'year'
displayFormats: {
hour: 'h:mm a',
day: 'ddd, MMM DD, YYYY',
week: 'dddd',
month: 'MMM'
},
tooltipFormat: 'dddd, MMM DD, YYYY' // <-- new in v3.x
},
ticks: {
minRotation: 80, // avoiding overlapping of x-Axis ticks
maxRotation: 90
}
},
y: { // <-- v3.x now object "{", not array "[{" anymore
ticks: {
beginAtZero: true,
callback: function (value) {
if (Number.isInteger(value)) return value;
}
},
suggestedMin: 0,
// the data maximum used for determining the ticks is Math.max(dataMax, suggestedMax)
suggestedMax: 10
}
}
};
const ctx = document.getElementById('chartJSContainer').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line',
data: yourData,
options: yourOptions
});
document.querySelector('#btnTime').addEventListener('click', () => {
myChart.options.scales['x'].type = 'time';
myChart.update();
});
document.querySelector('#btnTimeseries').addEventListener('click', () => {
myChart.options.scales['x'].type = 'timeseries';
myChart.update();
});
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script> -->
<!-- Obtain the most recent version of Chart.js, currently at v3.5.1 -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!-- To utilize x-Axis types 'time' or 'timeseries', additional libraries are required -->
<!-- (such as moment.js and its adapter) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment"></script>
<button id='btnTime'>time</button>
<button id='btnTimeseries'>timeseries</button>
<canvas id="chartJSContainer" width="600" height="400"></canvas>