最近.net項目需要做數據圖形統計功能,於是引入了HignCharts;選擇它主要是因爲其開源,且無第三方庫依賴。
我們的產品中需要用到的有餅圖和折線圖:
首先引入js:
<script src="../../code/highcharts.js"></script>
<script src="../../code/modules/exporting.js"></script>
<script src="../../code/modules/export-data.js"></script>
一、餅圖
餅圖的繪製比較簡單:
var pieChart = Highcharts.chart('container_pie', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
credits: {
enabled: false
},
colors:[
'#1E90FF', '#FFC125', '#CD5555', '#8B8B00', '#B4CDCD', '#9B30FF', '#7CFC00'
],
title: {
text: '各數據分類佔比'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
distance: -30,
format: '{point.percentage:.1f}%',
},
showInLegend: true
}
},
series: [{
name: '佔比',
colorByPoint: true,
data: [<% =PieData %>]
}]
});
這裏定製的地方主要有幾個,credits隱藏右下角標誌,colors餅圖各部分顯示的顏色,tooltip的pointFormat用於定製懸浮窗口下半部分的文字,plotOptions的format用於將數據轉換爲百分比,series中數據部分,由於我是.NET開發,用的aspx和cs,數據傳遞使用<% =PieData %>
二、折線圖
使用HignCharts後,折線圖的繪製也很簡單,但是,需要做一些個性化的修改
var lineChart = Highcharts.chart('container_line', {
chart: {
type: 'line'
},
credits: {
enabled: false
},
title: {
text: '趨勢圖'
},
colors:[
'#1E90FF', '#00CD00', '#EE3B3B', '#8B8B00', '#B4CDCD', '#9B30FF', '#7CFC00'
],
xAxis: {
type: 'datetime',
gridLineWidth:1,
dateTimeLabelFormats: {
day: '%Y-%m-%d'
},
tickPositions: [<% =LineXTickPositions %>],
labels: {
formatter: function(){
return Highcharts.dateFormat('%Y-%m-%d', this.value); //格式化x軸時間格式
}
},
},
yAxis: {
title: {
text: ''
},
gridLineWidth:1,
gridLineDashStyle:'Dash'
},
tooltip : {
formatter: function () {
return Highcharts.dateFormat('%Y-%m-%d',this.x)+'<br/><b>'+ this.series.name +':' + this.y+'<b/>';
}
},
plotOptions: {
line: {
dataLabels: {
// 開啓數據標籤
enabled: false
},
// 關閉鼠標跟蹤,對應的提示框、點擊事件會失效
enableMouseTracking: true
},
series: {
pointStart: <% =LineStartTime %>,
pointInterval: 24 * 3600 * 1000
}
},
series: [<% =LineData %>]
});
餅圖重複的部分就不說了,除此之外,還有一些需要定製的:
- 首先,x軸是時間:於是我們設置xAxis: { type: 'datetime' 然後我們需要設置間隔是變化的,可能1天,可能3天。但是無論設置tickInterval或者step都無法達到預想的效果。於是只有自己在後臺cs代碼中計算並傳遞tickPositions: [<% =LineXTickPositions %>],(這裏我們的需要是X軸最多10個)
- 然後需要設置x軸座標的格式:
labels: {
formatter: function(){
return Highcharts.dateFormat('%Y-%m-%d', this.value); //格式化x軸時間格式
}
},
- plotOptions的series中設置pointStart開始時間,pointInterval: 24 * 3600 * 1000表示每個數據間隔一天
- 點擊圖上的點,彈出彈窗也定製:
tooltip : {
formatter: function () {
return Highcharts.dateFormat('%Y-%m-%d',this.x)+'<br/><b>'+ this.series.name +':' + this.y+'<b/>';
}
},
- 上面有將時間格式化,Highcharts默認是utc時間,然後你們傳入的不是utc時間,可能導致少了8個小時,則需要在Highcharts.chart('container_line', {設置前加上Highcharts.setOptions({ global: { useUTC: false } });
原文:簡書ThinkinLiu 博客: IT老五
使用HighCharts確實很方便,除餅圖和折線圖以外,還有很多其他的圖形樣式可供選擇,API也很全;不過,他是商業收費的,這點需要注意。