Googlecharts-configuration-syntax
Google Chart-構成構文
この章では、Google Chart APIを使用してグラフを描画するために必要な構成を紹介します。
ステップ1:HTMLページを作成する
Google Chartライブラリを使用してHTMLページを作成します。
googlecharts_configuration
<html>
<head>
<title>Google Charts Tutorial</title>
<script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
</script>
<script type = "text/javascript">
google.charts.load('current', {packages: ['corechart']});
</script>
</head>
<body>
<div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
</div>
</body>
</html>
ここで、 container divは、Google Chartライブラリを使用して描画されたチャートを含むために使用されます。 ここでは、google.charts.loadメソッドを使用して、corecharts APIの最新バージョンをロードしています。
ステップ2:構成を作成する
Google Chartライブラリは、json構文を使用した非常に単純な構成を使用します。
//Instantiate and draw the chart.
var chart = new google.visualization.PieChart(document.getElementById('container'));
chart.draw(data, options);
ここで、データはJSONデータを表し、オプションは、Google Chartライブラリがdraw()メソッドを使用してコンテナdivでチャートを描画するために使用する構成を表します。 次に、さまざまなパラメーターを構成して、必要なJSON文字列を作成します。
タイトル
チャートのオプションを構成します。
//Set chart options
var options = {'title':'Browser market shares at a specific website, 2014',
'width':550,
'height':400};
データ表
チャートに表示されるデータを構成します。 DataTableは、チャートのデータを含む特別なテーブル構造化コレクションです。 データテーブルの列は凡例を表し、行は対応するデータを表します。 addColumn()メソッドは、最初のパラメーターがデータ型を表し、2番目のパラメーターが凡例を表す列を追加するために使用されます。 addRows()メソッドは、それに応じて行を追加するために使用されます。
//Define the chart to be drawn.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Browser');
data.addColumn('number', 'Percentage');
data.addRows([
['Firefox', 45.0],
['IE', 26.8],
['Chrome', 12.8],
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]);
ステップ3:チャートを描く
//Instantiate and draw the chart.
var chart = new google.visualization.PieChart(document.getElementById('container'));
chart.draw(data, options);
例
以下は完全な例です-
googlecharts_configuration
<html>
<head>
<title>Google Charts Tutorial</title>
<script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
</script>
<script type = "text/javascript">
google.charts.load('current', {packages: ['corechart']});
</script>
</head>
<body>
<div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
</div>
<script language = "JavaScript">
function drawChart() {
//Define the chart to be drawn.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Browser');
data.addColumn('number', 'Percentage');
data.addRows([
['Firefox', 45.0],
['IE', 26.8],
['Chrome', 12.8],
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]);
//Set chart options
var options = {'title':'Browser market shares at a specific website, 2014', 'width':550, 'height':400};
//Instantiate and draw the chart.
var chart = new google.visualization.PieChart(document.getElementById ('container'));
chart.draw(data, options);
}
google.charts.setOnLoadCallback(drawChart);
</script>
</body>
</html>
次のコードはdrawChart関数を呼び出して、Google Chartライブラリが完全にロードされたときにチャートを描画します。
google.charts.setOnLoadCallback(drawChart);
結果
結果を確認します。