highCharts解決日期型別在x軸顯示問題總結
阿新 • • 發佈:2019-01-28
廢話不多說,上程式碼。
在往highcharts裡面新增資料的時候,請注意日期格式,寫成t.getTime(),轉化成number格式,請參考JavaScript文件。其他就沒什麼了,歡迎糾錯。
var lengquebeng_copChartOption = { chart : { type : 'spline', backgroundColor : null, renderTo : 'lengquebeng_saveEnergyChart' }, plotOptions : { spline : { color : '#66CC00', dataLabels : { formatter : function() { return this.y * 100; } } } }, title : { text : null, }, xAxis : { type: 'datetime', dateTimeLabelFormats: { day: '%m-%d', }, tickPixelInterval: 150 , lineColor : '#FFF', tickColor : '#FFF', tickInterval :24 * 3600 * 1000, title : { align : 'high', text : '最近7日節能率', style : { color : '#EEE', fontSize : '11px' } }, labels : { rotation: -45, style : { color : '#FFF', font : '12px' } } }, credits : { enabled : false }, yAxis : { lineColor : '#FFF', tickColor : '#FFF', labels : { style : { color : '#FFF', font : '12px' } }, title : { text : '節能率(%)', style : { color : '#FFF', font : '12px' } }, gridLineDashStyle : 'dash' }, tooltip : { formatter: function () { return Highcharts.dateFormat('%m-%d',this.x)+'<br/>節能率:' + this.y.toFixed(2); } }, legend : { enabled : false }, series : [ {} ] }; var lengquebeng_copChart = new Highcharts.Chart(lengquebeng_copChartOption);
首先這是一個折線圖,在上面這串程式碼中,有作用的是下面這段
我們可以看出,在x軸定義上面需要定義type和dateTimeLabelFormats,type很明確能表達思,而dateTimeLabelFormats請參考我之前的 HighCharts日期及數值格式化xAxis : { type: 'datetime', dateTimeLabelFormats: { day: '%m-%d', }, tickPixelInterval: 150 , lineColor : '#FFF', tickColor : '#FFF', tickInterval :24 * 3600 * 1000, title : { align : 'high', text : '最近7日節能率', style : { color : '#EEE', fontSize : '11px' } }, labels : { rotation: -45, style : { color : '#FFF', font : '12px' } } }, credits : { enabled : false }, yAxis : { lineColor : '#FFF', tickColor : '#FFF', labels : { style : { color : '#FFF', font : '12px' } }, title : { text : '節能率(%)', style : { color : '#FFF', font : '12px' } }, gridLineDashStyle : 'dash' }, tooltip : { formatter: function () { return Highcharts.dateFormat('%m-%d',this.x)+'<br/>節能率:' + this.y.toFixed(2); } },
另外,我們需要注意到的是tooltip中Highcharts.dateFormat('%m-%d',this.x)這個,用語滑鼠碰上去提示框的顯示格式
。
資料的顯示
if(rs.saveEnergyChart && rs.saveEnergyChart.length > 0){ var datay = rs.saveEnergyChart.map(function(r, index, array) { t = new Date(r.time); v = r.value; return [t.getTime(), v ]; }); } console.log(datay); lengdongbeng_energyChart.series[0].setData(datax, true);
在往highcharts裡面新增資料的時候,請注意日期格式,寫成t.getTime(),轉化成number格式,請參考JavaScript文件。其他就沒什麼了,歡迎糾錯。