highcharts入門之Pie:如何讓Pie餅狀圖的圖例內顯示百分比(轉)
阿新 • • 發佈:2019-02-20
有很多人都在詢問如何在highcharts的pie 餅狀圖內顯示百分比,通過不斷琢磨最後得出了一個結論,只需要簡單配置即可實現這樣一個需求。
完整核心程式碼如下所示:
$(function () { var chart; //載入highcharts圖表 $(document).ready(function () { // Build the chart chart = new Highcharts.Chart({ chart: { renderTo: 'container',//裝載容器id plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false }, title: { text: 'highcharts餅圖實現圖例(Legend)的顯示' }, tooltip: { pointFormat: '{series.name}: <b>{point.percentage}%</b>', percentageDecimals: 1 //百分比保留小數 }, plotOptions: { pie: { allowPointSelect: true, //選中某塊區域是否允許分離 cursor: 'pointer', dataLabels: { enabled: true //是否直接呈現資料 也就是外圍顯示資料與否 }, showInLegend: true } }, legend: { layout: 'vertical', backgroundColor: '#FFFFFF', floating: true, align: 'left', verticalAlign: 'top', x: 90, y: 45, labelFormatter: function () { return this.name + '('+this.percentage+'%)'; } }, series: [{ type: 'pie', name: 'Browser share', data: [ ['Firefox', 45.0], ['IE', 26.8], { name: 'Chrome', y: 12.8, sliced: true, selected: true }, ['Safari', 8.5], ['Opera', 6.2], ['Others', 0.7] ] }] }); }); });
重中之重:
主要是需要在Legend標籤內對其顯示名稱進行格式化:
legend: { layout: 'vertical', backgroundColor: '#FFFFFF', floating: true, align: 'left', verticalAlign: 'top', x: 90, y: 45, labelFormatter: function () { return this.name + '('+this.percentage+'%)';//在名稱後面追加百分比資料 } },