Skip to content

Instantly share code, notes, and snippets.

@ksasao
Last active April 11, 2020 10:58
Show Gist options
  • Select an option

  • Save ksasao/85416a03545c4759512a4bade978b284 to your computer and use it in GitHub Desktop.

Select an option

Save ksasao/85416a03545c4759512a4bade978b284 to your computer and use it in GitHub Desktop.
Chart.js v2.0 time series line chart customization (legend, font size, labels, min/max, color, ...)
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<script src="https://unpkg.com/chartjs-plugin-colorschemes"></script>
<title>Chart.js - Time series line chart</title>
</head>
<body>
<canvas id="chart1"></canvas>
</body>
<script>
function updateAxes(chart, label, t_min,t_max, y_min,y_max) {
chart.options = {
scales: {
xAxes: [{
type: 'time',
time: {
min: t_min,
max: t_max,
displayFormats: {
second: 'HH:mm:ss',
minute: 'M/D HH:mm',
hour: 'M/D HH:mm',
day: 'M/D'
}
}
}],
yAxes: [{
scaleLabel: {
display: true,
fontStyle: 'bold',
fontSize: 20,
labelString: label
},
ticks: {
min: y_min,
max: y_max
}
}]
},
plugins: {
colorschemes: {
scheme: 'brewer.SetTwo8'
}
}
};
chart.update();
};
function addData(chart, data, item) {
if(!list.some(d => d.label == data)){
var newData = {
label: data,
lineTension: 0,
pointStyle: `circle`,
radius: 5,
borderWidth: 2,
fill: false,
data: []
};
list.push(newData);
}
chart.data.datasets.forEach((d) => {
if(d.label == data){
d.data.push(item);
// Remove old data
if(d.data[0].x < chart.options.scales.xAxes[0].time.min){
d.data.shift();
}
}
});
chart.update();
}
// Setup chart
let ctx = document.getElementById('chart1').getContext('2d');
let list = [];
Chart.defaults.global.defaultFontSize = 16;
var chart = new Chart(ctx, {
type: 'line',
data: { datasets: list },
options: {
legend: {
display: true,
labels: {
fontColor: 'rgb(64, 64, 64)'
}
},
}
});
// Update chart data
let a = 40.0;
let b = 38.0;
setInterval(function(){
const now = Date.now();
const old = new Date(now - (1000 * 60 * 1));
updateAxes(chart, 'Humidity (%RH)', old, now, 20,50);
a += Math.random() - 0.5;
b += Math.random() - 0.5;
addData(chart, '80DCDD98', { x: Date.now(), y: a });
addData(chart, '2A824A09', { x: Date.now(), y: b });
addData(chart, '平均', { x: Date.now(), y: (a+b)/2 });
},3000);
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment