Javascript google charts #1 area charts

google Chart api introduction

前言

製作後台時,常常需要把重要的資料呈現成圓餅圖、條狀圖、線性圖等等,這時我需要使用別人寫好的chart api來呈現這些資料,在使用之前必須參考google api的使用方法,這樣才能正確地使用。

前置作業

google chart api 使用說明:

https://developers-dot-devsite-v2-prod.appspot.com/chart/interactive/docs

範例

先以 area chart 為範例

程式碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
    <div id="chart_div" style="width: 100%; height: 500px;"></div>
       <script>  
        google.charts.load('current', {'packages':['corechart']}); //google charts載入封包corechart
        google.charts.setOnLoadCallback(drawChart); //設置要回呼的函數
  
        function drawChart() {
          var data = google.visualization.arrayToDataTable([
            ['Year', 'Bear', 'Cat','Dog'],['January',10,20,30],
            ['February ',15,23,32],['March',20,26,34],['April',25,29,36],
            ['May',30,32,38],['June',35,35,40],['July',40,38,42],
            ['August',45,41,44],['September',50,44,46],['October',55,47,48],
            ['November',60,50,50],['December',65,53,52]

          ]);
  
          var options = {
            title: '動物數量',
            hAxis: {title: 'Year',  titleTextStyle: {color: '#000'}},
            vAxis: {minValue: 0}
          };
  
          var chart = new google.visualization.AreaChart(document.getElementById('chart_div')); //可視化的類名稱的名稱
          chart.draw(data, options); //chart draw
        }
    </script>
</body>
</html>

result

結語

利用google chart api就可以美化資料,讓觀看者或客戶能夠不用看純文字的資料,有更好的使用者體驗