jQuery - Use Highcharts API to draw multiple charts dynamically

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

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

的範例操作,非常清楚!

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

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

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

var option_thumb = {
   chart: {
       type: 'line'
   },
   title: {
       text: '',
       style: {
            color: '#000000',
            font: 'bold 20px Trebuchet MS, Verdana, sans-serif',
       },
       align: 'center'
   },
   legend: {
       layout: 'vertical',
       align: 'center',
       verticalAlign: 'top',
       x: 0,
       y: 20,
       borderWidth: 0
   },
   xAxis: {
       categories:[],
       labels: {
            rotation: 90,
            style: {
                    color: '#000000',
                    font: 'bold 11px Trebuchet MS, Verdana, sans-serif',
            },
            align:"left",
       },
       title:{
            style: {
                    color: '#000000',
                    font: 'bold 14px Trebuchet MS, Verdana, sans-serif'
                }
            },
   },
   yAxis: {
       title: {
           text: 'Express',
           style: {
                color: '#000000',
                font: 'bold 18px Trebuchet MS, Verdana, sans-serif'
           }
       },
       labels: {
           style: {
                color: '#000',
                font: 'bold 14px Trebuchet MS, Verdana, sans-serif'
           }
       }
   },
   credits : {
       enabled : false
   },
   plotOptions: {
       series: {
            marker: {
                fillColor: '#FFFFFF',
                lineWidth: 4,
                lineColor: null // inherit from series
            }
       }
   },
   series: [{
       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],
       color: '#004EA0'
   }]
};

請注意,由於要動態產生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,放大字體大小!

var thumb_options = new Object();

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

忘了補上css
.show_chart{
    width: 500px; 
    height: 300px;  
    cursor:pointer;
}

留言

張貼留言