'How to set vertical lines for new day on x-axis in ChartJS v3.x
I have a graph that displays data of the last 2h, 8h, 24h, or 48h. This can be changed via buttons on the webpage. When the timespan includes midnight, I would like to display vertical lines with little labels (maybe at hover) at midnight displaying the date (or day of the week) of the upcoming day.
I have not found any resources on how to do that in Chartjs 3. How would I do such a task?
This is how I create the graph. "time" is an array of epoch times:
chart = new Chart(
document.getElementById('Chart'),
{
type: 'line',
data:
{
labels: time,
datasets: [
{
label: dataObjects[start].label,
backgroundColor: dataObjects[start].backgroundColor,
borderColor: dataObjects[start].borderColor,
fill: dataObjects[start].fill,
data: dataObjects[start].data,
yAxisID: 'A',
}]
},
options: {
elements: {point: {radius: 0.5, borderWidth: 1},
line: {borderWidth: 3}},
maintainAspectRatio: false,
scales: {
x:
{
//max: last_time,
type: "time",
grid: {borderColor: color.time},
ticks: {color: color.time},
time: {
unit: 'hour',
tooltipFormat: 'dd.MM. HH:mm',
displayFormats: {
second: "HH:mm",
minute: "HH:mm",
hour: "HH:mm",
day: "d.MM.",
week: "d.MM."
},
}
},
A:
{
type: 'linear',
grid: {borderColor: color.time},
position: 'left',
ticks: {color: color.time},
suggestedMin: dataObjects[start].suggestedMin,
suggestedMax: dataObjects[start].suggestedMax,
title: {text: dataObjects[start].text,
display: true,
color: color.time}
}
},
plugins: {
legend: {display: false}
}
}
});
Solution 1:[1]
You can use a mixed chart to create this graph mixing a line chart and a bar chart.
Here you can view one example:
https://codepen.io/alyf-mendonca/pen/dyZZoeB
HTML:
<div>
<canvas id="myChart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
JS:
const labels = [
'January',
'February',
'March',
'April',
'May',
'June',
];
const data = {
labels: [
'20:00',
'21:00',
'22:00',
'23:00',
'00:00',
'01:00',
'02:00'
],
datasets: [{
type: 'line',
label: 'Bar Dataset',
data: [20, 21, 23, 22, 21, 20, 23],
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgba(255, 99, 132, 0.2)'
}, {
type: 'bar',
label: 'Line Dataset',
data: [0, 0, 0, 0, 50, 0, 0],
fill: false,
borderColor: 'rgb(54, 162, 235)'
}]
};
const config = {
type: 'bar',
data: data,
options: {
scales: {
x: {
stacked: true
}
}
},
};
const myChart = new Chart(
document.getElementById('myChart'),
config
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alyf Mendonça |
