Chart.js ToolTip のカスタマイズはネット検索すれば、まとまった解説も沢山見つかるし、サンプルもある。
http://tr.you84815.space/chartjs/configuration/tooltip.html
あえて、時刻をX軸にしたグラフで ToolTipカスタマイズを書いてみた。
options に、tooltips: { ... } を書くことになる。ToolTip のタイトルやラベルは、
callback で、
title: function(tooltipItem, data){
return "タイトル";
},
label: function(tooltipItem, data){
return "ラベル";
},
というようにする。tooltipItemは対象データ、data はグラフデータ全体、
tooltipItem.index で並んだデータ配列のインデックスを参照できる。
サンプル、moment.js を使ってます。
var graph = {
xLabels: [],
yLabels: [],
datasets: [{
label: "First dataset",
lineTension: 0,
:
省略
:
};
var options = {
responsive: true,
title:{ display:true,
text:'Time-Line Chart sample'
},
scales: {
xAxes: [{ display: true,
scaleLabel: { display: true, labelString: '時刻' },
type: "time",
time: {
unit: "hour",
displayFormats:{ hour: 'HH:mm' },
min: new moment().hour(5).minute(0).second(0).millisecond(0),
max: new moment().hour(17).minute(0).second(0).millisecond(0),
},
}],
yAxes: [{ display: true,
scaleLabel: { display: true, labelString: 'Value' },
ticks: { min: 0, max: 100, stepSize: 20 }
}]
},
tooltips: {
titleFontSize: 18,
bodyFontSize: 18,
callbacks: {
title: function (tooltipItem, data){
return "First";
},
label: function (tooltipItem, data){
return moment(tooltipItem.xLabel._i).format('YYYY年M月D日 HH:mm:ss')
+ " value = "
+ tooltipItem.y;
}
}
},
legend:{
onClick: function(){ return false; },
},
};
var canvas = document.getElementById("myChart");
var ctx = canvas.getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: graph,
options: options
});
var todaystr = new moment().format('YYYY-MM-DDT');
graph.datasets[0].data.push({ t: moment(todaystr + "05:17:20"), y: createRandom(0, 100) });
graph.datasets[0].data.push({ t: moment(todaystr + "06:43:52"), y: createRandom(0, 100) });
graph.datasets[0].data.push({ t: moment(todaystr + "07:21:05"), y: createRandom(0, 100) });
graph.datasets[0].data.push({ t: moment(todaystr + "08:06:12"), y: createRandom(0, 100) });
graph.datasets[0].data.push({ t: moment(todaystr + "09:47:41"), y: createRandom(0, 100) });
graph.datasets[0].data.push({ t: moment(todaystr + "10:02:33"), y: createRandom(0, 100) });
graph.datasets[0].data.push({ t: moment(todaystr + "11:12:02"), y: createRandom(0, 100) });
graph.datasets[0].data.push({ t: moment(todaystr + "12:11:02"), y: createRandom(0, 100) });
graph.datasets[0].data.push({ t: moment(todaystr + "13:12:28"), y: createRandom(0, 100) });
graph.datasets[0].data.push({ t: moment(todaystr + "14:16:41"), y: createRandom(0, 100) });
myChart.update();
label: function は、以下のように長いのが正解なのかもしれないが上の方が、簡潔
label: function (tooltipItem, data){
return moment(graph.datasets[0].data[tooltipItem.index].t._i).format('YYYY年M月D日 HH:mm:ss')
+ " value = "
+ graph.datasets[0].data[tooltipItem.index].y;
}