Setting the “unit” option for the time scale
We focus on configuring the granularity of time intervals displayed on the x-axis by setting the unit option for the time scale in Chart.js.In this approach, emphasis is placed on configuring the time scale of a Chart.js chart to display data aggregated by a specific time unit, such as month. By setting the unit option, the chart effectively organizes temporal data into meaningful intervals, providing clarity and insight into trends over time.
Syntax:
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day' // or 'month', 'year', etc.
}
}]
}
Example: Monthly Time Series Line Chart
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chart.js Time Scale Approach 2</title>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.0/Chart.bundle.min.js">
</script>
</head>
<style>
* {
background-color: bisque;
}
</style>
<body>
<h1 style="color: aqua;">
Time Scale Approach 1| w3wiki
</h1>
<canvas id="myChart"></canvas>
<script>
window.onload = function () {
let ctx =
document.getElementById("myChart").getContext("2d");
// Sample data
let data = {
labels: ["2023-03-01", "2023-03-02", "2023-03-03", "2023-03-04", "2023-03-05"],
datasets: [{
label: "My First dataset",
data: [12, 19, 3, 5, 2],
}]
};
let chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day' // or 'month', 'year', etc.
}
}]
}
}
});
}
</script>
</body>
</html>
Output:
How to Format X Axis Time Scale Values in ChartJS ?
In Chart.js, formatting the x-axis time values involves searching for ways to present temporal data effectively. By default, Chart.js supports time series data and provides powerful options to customize the appearance of time labels on the x-axis.
There are several approaches to format x-axis time scale values in Chart.js which are as follows:
Table of Content
- Using the time type for the x-axis scale configuration
- Setting the unit option for the time scale
- Customizing time label display formats
CDN Link:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.0/Chart.bundle.min.js"></script>