LoginSignup
5
9

More than 5 years have passed since last update.

Google Chartsを使って,2つのy軸にプロットする

Posted at

やりたいこと

CakePHP2から出てきたデータをGoogle Chartsでプロットする.

このときに左右の異なるy軸をもつようにプロットしたい.
例えばテスト結果をプロットするなら以下のようにしたい.
左y軸: 解答率
右y軸: 解答スピード

Google Charts ?

Googleの提供するjavascriptのグラフ描画ライブラリ
https://developers.google.com/chart/interactive/docs/

コード

script.js
 <script type="text/javascript" src="https://www.google.com/jsapi"></script>
 <script type="text/javascript">
 google.load("visualization", "1", {packages:["corechart"]});
 google.setOnLoadCallback(drawChart);
 function drawChart() {
     var data = google.visualization.arrayToDataTable(<?php echo $data ?>);
     // CakePHPから出てくる配列は,以下のようになっている.
     // $data[0] = array('x label', 'y1 label', 'y2 label');
     // forで幾つかのデータを入れる
     // array_push($data, array('x data', 'y1 data', 'y2 data'))

     var options = {
         chartArea: {'width': '600', 'height': '450'},
         series: {
             0: {targetAxisIndex:0}, // 第1系列は左のY軸を使用
             1: {targetAxisIndex:1}, // 第2系列は右のY時を使用
         },
         hAxis: {title: 'Day', minValue: 0, maxValue: 32}, // x軸のラベル
         vAxes: {
             // Add labels to each y axis.
             0: {
                 title: 'y1',
                 minValue: 0
             },
             1: {
                 title: 'y2',
                 minValue: 0
             }
         },
     };

     var chart = new google.visualization.LineChart(document.getElementById('daily_chart'));
     chart.draw(data, options);
 }
 </script>

 <div id="daily_chart" style="width: 700px; height: 600px"></div>

5
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
9