当前位置: 首页 > 后端技术 > PHP

Highcharts+PHP+Mysql生成饼图

时间:2023-03-30 06:08:01 PHP

Demo下载地址:http://www.erdangjiade.com/js...效果图:Mysql首先我们建一个chart_pie表作为统计数据。----表结构`chart_pie`--如果不存在`chart_pie`(`id`int(11)NOTNULLAUTO_INCREMENT,`title`varchar(30)NOTNULL,`pv`int(10)NOTNULL,主键(`id`))ENGINE=MyISAMDEFAULTCHARSET=utf8AUTO_INCREMENT=7;----转储表格数据`chart_pie`--INSERTINTO`chart_pie`(`id`,`title`,`pv`)VALUES(1,'Baidu',1239),(2,'google',998),(3,'搜搜',342),(4,'必应',421),(5,'搜狗',259),(6,'其他',83);PHP在pie.php中,我们需要生成数据供前端调用:$query=mysql_query("select*fromchart_pie");while($row=mysql_fetch_array($query)){$arr[]=array($row['title'],intval($row['pv']));}$data=json_encode($arr);jQuery$(function(){$('#highcharts').highcharts({chart:{renderTo:'chart_pie',//饼图关联的html元素id值defaultSeriesType:'pie',//默认图表类型为饼图plotBackgroundColor:'#ffc',//设置图表区域背景色plotShadow:true//设置阴影},title:{text:'搜索引擎统计分析'//图表标题},credits:{text:'erdangjiade.com'},tooltip:{formatter:function(){//鼠标滑动到图片提示框的formatterreturn''+this.point.name+':'+twoDecimal(this.percentage)+'%';}},plotOptions:{pie:{allowPointSelect:true,//允许选择,点击选中扇区分离显示cursor:'pointer',//当鼠标指向扇形区域时,变成手形(clickable)//showInLegend:true,//如果要显示图例,可以将此项设置为truedataLabels:{enabled:true,//设置数据标签Visible,即每个扇区对应的数据被展示color:'#000000',//数据显示颜色connectorColor:'#999',//设置数据字段扇形区域连接线的颜色style:{fontSize:'12px'//数据显示的大小},formatter:function(){//格式化数据return''+this.point.name+':'+twoDecimal(this.percentage)+'%';//return''+this.point.name+':'+this.y;}}}},series:[{//数据列名:'搜索引擎',data:data//核心数据列是从php读取的数据并解析成JSON}]});});另外格式化数据城市,如果要显示百分比,可以使用this.percentage,Highcharts会自动将整数转为百分比,如果要显示数据量,直接使用this.y百分比代码如下:formatter:function(){//格式化数据return''+this.point.name+':'+twoDecimal(this.percentage)+'%';}实际数据是这样的:formatter:function(){//格式化数据return''+this.point.name+':'+this.y;}最后,我们要保留两位小数,代码粘贴:functiontwoDecimal(x){//保留2位小数varf_x=parseFloat(x);if(isNaN(f_x)){alert('错误的参数');返回假;}varf_x=Math.round(x*100)/100;vars_x=f_x.toString();varpos_decimal=s_x.indexOf('.');如果(pos_decimal<0){pos_decimal=s_x.length;s_x+='.';}while(s_x.length<=pos_decimal+2){s_x+='0';}返回s_x;}