接上一篇 HighCharts筆記之: Bar Chart,這一篇繼續記錄在項目中使用 Pie Chart 的情況,只是自己的一點總結和記錄,以備日后翻閱。這一次是通過頁面上的表格(Table)數據,生成對應的餅圖(Pie Chart),具體實現如下:
Pie Chart
HTML Code
<body> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">${title}</h3> </div> <div class="modal-body"> <div id="container2" style="width: 100%; height: 280px"></div> <table id="datatable" class="table table-striped table-bordered table-hover table-condensed"> <thead> <tr> <th>User</th> <th>${title}</th> </tr> </thead> <tbody> <c:forEach items="${userSum}" var="item"> <tr> <th>${item.user }</th> <td>${item.sum }</td> </tr> </c:forEach> </tbody> </table> </div> <div class="modal-footer"> <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> </div> </body>
Javascript Code
var chart; Highcharts.visualize = function(table, options) { // the data series options.series = []; var l= options.series.length; options.series[l] = { name: '${title}', data: [] }; $('tbody tr', table).each( function(i) { var tr = this; var th = $('th', tr).text(); var td =parseFloat($('td', tr).text()); options.series[0].data.push({name:th,y:td}); }); chart = new Highcharts.Chart(options); } // On document ready, call visualize on the datatable. $(document).ready(function() { var table = document.getElementById('datatable'), options = { chart: { renderTo: 'container2', defaultSeriesType: 'pie' }, title: { text: '${title}' }, tooltip: { formatter: function() { return '<b>'+ this.series.name +'</b><br/>'+ this.point.name +' '+ this.y; } }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer' } } }; Highcharts.visualize(table, options); });
這種做法在 Coding 時會更簡潔,但在實際運行時效率不高,因為 Pie Chart 需要等待頁面上的數據都生成時才能呈現,所以總是給用戶一種遲滯感,所以個人感覺還是通過 JSon 的方式生成圖表更好(更快)。