前回、Androidのライブラリを使ってグラフの描画を行いましたが、
webアプリでもグラフを表示することになりました。
Angular.jsを利用しているため、相性が良さそうなangular-google-chartを触ってみます
下準備
ライブラリを追加し、読み込みます。
bower.json
{ "dependencies": { "angular-google-chart": "^0.1.0" } }
index.html
<script src="bower_components/angular-google-chart/ng-google-chart.js"></script>
app.js
angular .module('feApp', [ 'googlechart' ]);
View
hoge.html
<div class="col-xs-12"> <div class="row"> <div google-chart chart="hoge.pie" style="width: 700px; height: 400px;" class="center-block"></div> </div> </div> <div class="col-xs-12"> <div class="row"> <div google-chart chart="hoge.bar" style="width: 700px; height: 400px;" class="center-block"></div> </div> </div>
Controller
angular.module('feApp') .controller('HogeController', function() { // データ格納オブジェクト this.pie = {}; this.bar = {}; var colors = [ "#e74c3c", "#3498db", "#f1c40f", "#2ecc71", "#e67e22", "#1abc9c", "#9b59b6", "#34495e", "#95a5a6" ]; var items = [{ Color: "Red", Count: 1 }, { Color: "Blue", Count: 4 }, { Color: "Yellow", Count: 2 }, { Color: "Green", Count: 3 }, { Color: "Orange", Count: 3 }, { Color: "BlueGreen", Count: 4 }, { Color: "Purple", Count: 1 }, { Color: "BlueGray", Count: 3 }, { Color: "Gray", Count: 2 }]; // 円グラフ this.createPieChart = function() { this.pie.data = [ ['Color', "Count", { role: 'style' }] ]; Array.prototype.push.apply(this.pie.data, items.map(function(e, i) { return [e.Color, e.Count, colors[i]]; })); this.pie.type = "PieChart"; }; // 棒グラフ this.createBarChart = function() { this.bar.data = [ ['Color', "Count", { role: 'style' //色をデフォルトから変更 }] ]; Array.prototype.push.apply(this.bar.data, items.map(function(e, i) { return [e.Color, e.Count, colors[i]]; })); //グラフの種類 this.bar.type = "BarChart"; this.bar.options = { titlePosition: "none", legend: { position: 'none' }, chartArea: { width: '60%', height: '80%' }, animation: { duration: 1000, easing: 'out', startup: true, //アニメーションの起動 }, }; }; this.createPieChart(); this.createBarChart(); });
表示結果
データオブジェクトの型に悩まなくて済む分、Androidよりも楽に表示できました。
円グラフがアニメーションに対応していないそうなのでゴリゴリ動かしたいアプリには不向きかもしれませんが、サクッとグラフ表示したいときはおすすめです。