圆饼图是用于看各组资料间的比例,用Flot绘制圆饼图相当简单,不过Flot需要加入jquery.flot.pie.js插件才能给制圆饼图,我们沿用上一章用过的世界人口数据来当作圆饼图的数据源,并且加入一些互动功能呈现.
圆饼图范例 (世界人口比例)
圆饼图资料
因为Flot不支持圆饼图,所以必须加入圆饼图的插件jquery.flot.pie.js,此范例会用到的档案清单如下.<script type="text/javascript" src="/js/jquery-1.8.3.min.js"></script> <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="/js/flot/excanvas.min.js"></script><![endif]--> <script type="text/javascript" src="/js/flot/jquery.flot.js"></script> <script type="text/javascript" src="/js/flot/jquery.flot.pie.js"></script>
<div id="flot-placeholder" style="width:400px;height:300px"></div>
var dataSet = [ {label: "Asia", data: 4119630000, color: "#005CDE" }, { label: "Latin America", data: 590950000, color: "#00A36A" }, { label: "Africa", data: 1012960000, color: "#7D0096" }, { label: "Oceania", data: 35100000, color: "#992B00" }, { label: "Europe", data: 727080000, color: "#DE000F" }, { label: "North America", data: 344120000, color: "#ED7B00" } ];
圆饼图选项
圆饼图的选项设定都在series.pie里,要让Flot绘制圆饼图就要设定series.pie.show为true.另外我们自定义了圆饼图的标签,默认圆饼图会自动显示图例,但如果你想改成显示卷标时,可设定legend.show为false,Flot就不会显示图例而改显示卷标.标签部份我们更改了几个地方,label.radius是设定标签出现在圆饼图的半径位置,如果值是设置0到1之间,那就会用作容器可用空间大小的百分比,如果值是设定大于等于1的话,则会用作像素.
另外我们自定义了label.formatter,此函式可用来自定义显示卷标.我们还设定了label.background.opacity,用来指定标签背景的透明度,而label.background.color则用来设定标签背景颜色.
series: { pie: { show: true, label: { show:true, radius: 0.8, formatter: function (label, series) { return '' + label + ' : ' + Math.round(series.percent) + '%'; }, background: { opacity: 0.8, color: '#000' } } } }
圆饼图互动功能
因为圆饼图卷标默认只能显示百分比数据,但如果我们想要知让用户鼠标移到圆饼图区块上就可以显示该区块的原始数据的话,可以用Flot内建的"plothover"事件来完成.首先我们先在定位点下方插入一个div,并给与一个id名称flot-memo.<div id="flot-memo" style="text-align:center;height:30px;width:250px;height:20px;text-align:center;margin:0 auto"></div>
grid: { hoverable: true }
$.fn.showMemo = function () { $(this).bind("plothover", function (event, pos, item) { if (!item) { return; } var html = []; var percent = parseFloat(item.series.percent).toFixed(2); html.push("<div style=\"border:1px solid grey;background-color:", item.series.color, "\">", "<span style=\"color:white\">", item.series.label, " : ", $.formatNumber(item.series.data[0][1], { format: "#,###", locale: "us" }), " (", percent, "%)", "</span>", "</div>"); $("#flot-memo").html(html.join('')); }); }
$(document).ready(function () { $.plot($("#flot-placeholder"), dataSet, options); $("#flot-placeholder").showMemo(); });
其它圆饼图
圆饼图还支持其它不同的类型,以下展示几种不同类型的圆饼图
倾斜圆饼图范例
倾斜圆饼图选项程序代码
var options = { series: { pie: { show: true, tilt: 0.5 } } };
甜甜圈圆饼图范例
甜甜圈圆饼图选项程序代码
var options = { series: { pie: { show: true, innerRadius: 0.5, label: { show: true } } } };