jQuery - Use Highcharts API to draw multiple charts dynamically

在這邊要提到的是如何利用Highcharts API來動態製作多個圖表,根據當下的需求。在這邊並

會提到關於Highcharts的options如何設定及介紹,可以查閱官網的documents,裡面有很多實際

的範例操作,非常清楚!

首先,我們先定義要放置chart圖表的外層容器,在這邊是打算利用table

  1. <table id="charts" style="width:600px"></table>

接著定義簡單的options,如下:

  1. var option_thumb = {
  2. chart: {
  3. type: 'line'
  4. },
  5. title: {
  6. text: '',
  7. style: {
  8. color: '#000000',
  9. font: 'bold 20px Trebuchet MS, Verdana, sans-serif',
  10. },
  11. align: 'center'
  12. },
  13. legend: {
  14. layout: 'vertical',
  15. align: 'center',
  16. verticalAlign: 'top',
  17. x: 0,
  18. y: 20,
  19. borderWidth: 0
  20. },
  21. xAxis: {
  22. categories:[],
  23. labels: {
  24. rotation: 90,
  25. style: {
  26. color: '#000000',
  27. font: 'bold 11px Trebuchet MS, Verdana, sans-serif',
  28. },
  29. align:"left",
  30. },
  31. title:{
  32. style: {
  33. color: '#000000',
  34. font: 'bold 14px Trebuchet MS, Verdana, sans-serif'
  35. }
  36. },
  37. },
  38. yAxis: {
  39. title: {
  40. text: 'Express',
  41. style: {
  42. color: '#000000',
  43. font: 'bold 18px Trebuchet MS, Verdana, sans-serif'
  44. }
  45. },
  46. labels: {
  47. style: {
  48. color: '#000',
  49. font: 'bold 14px Trebuchet MS, Verdana, sans-serif'
  50. }
  51. }
  52. },
  53. credits : {
  54. enabled : false
  55. },
  56. plotOptions: {
  57. series: {
  58. marker: {
  59. fillColor: '#FFFFFF',
  60. lineWidth: 4,
  61. lineColor: null // inherit from series
  62. }
  63. }
  64. },
  65. series: [{
  66. data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
  67. color: '#004EA0'
  68. }]
  69. };

請注意,由於要動態產生chart,因此在options內的chart object並不會事先指定renderTo容器!

再來是定義thumb_options object,以現有option設定做deep copy assign to it,並且在此指定產生

4張圖,產生<tr></tr>及<td></td>。最後要特別提到的是new Highcharts下的Chart function

Chart (Object options, Function callback)

請注意callback,當圖表完成載入後,您可以再去調整圖表的項目,在這邊是示範

調整Series 1 text,放大字體大小!

  1. var thumb_options = new Object();
  2. for(var i = 0 ; i < 4 ; i++){
  3. //deep copy elements
  4. thumb_options[i] = $.extend(true, {}, option_thumb);
  5. //set thumbnail chart container
  6. thumb_options[i].chart.renderTo = "container"+i;
  7. thumb_options[i].title.text = "chart "+i;
  8. if($("#charts tr").get().length < 2)
  9. $("#charts").append("");
  10. $("#charts tr:nth-child("+((i%2)+1)+")").append("<td><div id='container"+i+"' class='show_chart'></div></td>");
  11. //initialize highchart
  12. new Highcharts.Chart(thumb_options[i], function(){
  13. $(".highcharts-legend-item").find("text").each(function(){
  14. $(this).children().css("font-size", "24px");
  15. });
  16. });
  17. }

忘了補上css
  1. .show_chart{
  2. width: 500px;
  3. height: 300px;
  4. cursor:pointer;
  5. }

留言

張貼留言