Replies: 2 comments
|
I would suggest to explore Timeseries option instead: https://www.youtube.com/watch?v=R9JE5fQMlL0 |
0 replies
|
Yes! Chart.js supports irregular time intervals using the time scale. Here is how to set it up: 1. Install the date adapter: npm install chartjs-adapter-date-fns2. Configure the chart: import "chartjs-adapter-date-fns";
const chart = new Chart(ctx, {
type: "line",
data: {
datasets: [{
data: [
{ x: "2024-01-01", y: 10 },
{ x: "2024-01-03", y: 20 }, // 2 days gap
{ x: "2024-01-10", y: 15 }, // 7 days gap
{ x: "2024-01-15", y: 25 }, // 5 days gap
{ x: "2024-02-01", y: 30 } // 17 days gap
],
borderColor: "#3b82f6",
fill: false
}]
},
options: {
scales: {
x: {
type: "time",
time: {
unit: "day", // or "week", "month", "year"
displayFormats: {
day: "MMM dd",
week: "MMM dd",
month: "MMM yyyy"
}
},
title: {
display: true,
text: "Date"
}
},
y: {
beginAtZero: true
}
},
plugins: {
tooltip: {
callbacks: {
title: function(context) {
return new Date(context[0].parsed.x).toLocaleDateString();
}
}
}
}
}
});3. Auto-detect time unit: If you want Chart.js to automatically choose the best time unit: scales: {
x: {
type: "time",
time: {
// Let Chart.js auto-detect the best unit
unit: false
},
ticks: {
source: "auto",
autoSkip: true,
maxTicksLimit: 10
}
}
}4. For different date formats in your data: // Your data can be in any format
const data = [
{ x: new Date("2024-01-01"), y: 10 },
{ x: "2024-01-03T10:30:00", y: 20 },
{ x: 1704672000000, y: 15 } // Unix timestamp
];5. Custom tick formatting: ticks: {
callback: function(value, index, ticks) {
const date = new Date(value);
return date.toLocaleDateString("en-US", {
month: "short",
day: "numeric"
});
}
}This will properly handle irregular time intervals and display the x-axis with appropriate time units. |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
The dataset contains different date for each chart, want the tick mark scale base of the date range from the dataset.
All reactions