前陣子公司的專案有個需求:用 Highcharts 做一個餅圖,同時顯示每個區塊的數量與百分比。剛入門的我一時不知從何下手,上網翻了些資料後整理出這份範例,記錄下來備用。
<div class="piecleft" id="chart" style="height:350px; width: 350px;"> </div> <script type="text/javascript" charset="utf-8"> var chart; $(document).ready(function() { chart = new Highcharts.Chart({ chart: { renderTo: 'chart' }, title: { text: '版本分布分析' }, plotArea: { shadow: null, borderWidth: null, backgroundColor: null }, tooltip: { formatter: function() { return '<b>'+ this.point.name +'</b>: '+ Highcharts.numberFormat(this.percentage, 1) +'% ('+ Highcharts.numberFormat(this.y, 0, ',') +' 個)'; } }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, formatter: function() { if (this.percentage > 4) return this.point.name; }, color: 'white', style: { font: '13px Trebuchet MS, Verdana, sans-serif' } } } }, legend: { backgroundColor: '#FFFFFF', x: 0, y: -30 }, credits: { enabled: false }, series: [{ type: 'pie', name: 'Browser share', data: [ ['1.1',3617], ['1.2.1',3436], ['1.0',416], ['1.3',2], ['1.2',1], ['新增對比',5000] ] }] }); }); </script>
關鍵在於 tooltip.formatter 與 dataLabels.formatter:前者負責游標移入時同時顯示百分比與數量,後者則控制標籤顯示,並可用 this.percentage > 4 這類條件過濾掉占比過小的區塊,避免標籤互相重疊。
感謝閱讀,希望這份範例能幫到大家。