echarts畫圓環統計圖並載入動態資料 (ajax獲取資料)
最近,要用到echarts畫餅圖統計圖,於是學習了會,附上echarts官網
http://echarts.baidu.com/doc/example.html
看到echarts有一些餅圖例項,程式碼如下:
option = {
tooltip : {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)"
},
legend: {
orient : 'vertical',
x : 'left',
data:['直接訪問','郵件營銷','聯盟廣告','視訊廣告','搜尋引擎']
},
toolbox: {
show : true,
feature : {
mark : {show: true},
dataView : {show: true, readOnly: false},
magicType : {
show: true,
type: ['pie', 'funnel'],
option: {
funnel: {
x: '25%',
width: '50%',
funnelAlign: 'center',
max: 1548
}
}
},
restore : {show: true},
saveAsImage : {show: true}
}
},
calculable : true,
series : [
{
name:'訪問來源',
type:'pie',
radius : ['50%', '70%'],
itemStyle : {
normal : {
label : {
show : false
},
labelLine : {
show : false
}
},
emphasis : {
label : {
show : true,
position : 'center',
textStyle : {
fontSize : '30',
fontWeight : 'bold'
}
}
}
},
data:[
{value:335, name:'直接訪問'},
{value:310, name:'郵件營銷'},
{value:234, name:'聯盟廣告'},
{value:135, name:'視訊廣告'},
{value:1548, name:'搜尋引擎'}
]
}
]
};
這邊資料是寫死的,335,310等,那麼如何動態加入資料,使之成為動態的統計圖呢?
$(function() {
var jobChart, ageChart, progressChart;
function drawCharts(data) {
var jobOption = {
title: {
text: '員工在職情況',
x: 'center',
y: 10,
textStyle: {
fontSize: 16,
fontWeight: 'bolder',
color: '#4b4b4b'
}
},
legend: {
orient: 'horizontal',
x: 'center',
y: 'bottom',
itemWidth: 6,
itemHeight: 12,
selectedMode: false,
data: ['正式員工', '試用員工', '實習/兼職']
},
calculable: false,
series: [
{
name: '在職人數',
type: 'pie',
radius: ['40%', '50%'],
itemStyle: {
normal: {
label: {
position: 'center',
distance: 8,
textStyle: {
color: '#4b4b4b',
fontSize: '14'
},
formatter: function(){
return "在職人數" + "\n" + data.jobUserCount + "人"
}
},
labelLine: {
show: false
}
},
emphasis: {
label: {
show: true,
position: 'outer',
textStyle: {
align: 'center',
baseline: 'middle',
fontSize: '12'
},
formatter: function(params){
return params.name +'\n'+ params.value +' ('+ params.percent +'%)';
}
},
labelLine: {
show: false,
length: 16
}
}
},
data: [{
value: data.formalUserCount,
name: '正式員工',
itemStyle: {
normal: {
color: '#8bcfb8'
}
}
},{
value: data.tryoutUserCount,
name: '試用員工',
itemStyle: {
normal: {
color: '#efb43e'
}
}
},{
value: data.internshipUserCount,
name: '實習/兼職',
itemStyle: {
normal: {
color: '#64bdec'
}
}
}]
}
]
};
jobChart.setOption(jobOption);
};
require.config({
paths: {
echarts: '/static/lib/echarts'
}
});
require(
[
'echarts',
'echarts/chart/pie'
],
function (ec) {
jobChart = ec.init(document.getElementById('pieJob'));
ageChart = ec.init(document.getElementById('pieAge'));
progressChart = ec.init(document.getElementById('pieProgress'));
$.ajax({
type: 'POST',
url: '/count/statistics.json', //ajax請求的url連結
dataType: 'json', //資料格式
success: function (json) {
if (json.code == 1) {
drawCharts(json.data);//當ajax獲取資料成功,載入畫圖方法
}
}
});
}
);
});