We are going to use Chartjs to plot our samples (values over time) in a Line Chart but before we are going to double our samples. To create each new sample we take the date (x) of the next element and the value (y) of the previous one.
JavaScript HTML CSSconst data = [{
"date": "2097-06-24 00:00:00",
"value": 80
}, {
"date": "2097-06-24 04:00:00",
"value": 70
}, {
"date": "2097-06-24 18:00:00",
"value": 40
}, {
"date": "2097-06-24 22:00:00",
"value": 80
}, {
"date": "2097-06-24 23:10:00",
"value": 100
}]
const chart = (() => {
/**
* Load data
* @param data [array]
*/
function load(data) {
const ctx = document.getElementById("myChart").getContext('2d')
let myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Value',
lineTension: 0,
data: data.map(m => {
return {
x: m.date,
y: m.value
}
})
.reduce((acc, m, i, a) =>
acc.concat(m, {
x: a[i + 1] ? a[i + 1].x : m.x,
y: m.y
}), []),
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1
}]
},
options: {
title: {
display: true,
text: 'Chart'
},
scales: {
xAxes: [{
type: 'time',
display: true,
scaleLabel: {
display: true,
labelString: 'Date'
}
}],
yAxes: [{
display: true,
stacked: true,
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
}
}
});
}
return {
load: load
};
})();
chart.load(data);
<canvas id="myChart"></canvas>
#myChart {
width: 100%;
height: 100%;
}