在本章中,我们将展示使用Google Chart API绘制图表所需的配置.
使用Google图表库创建一个HTML页面.
googlecharts_configuration.htm
<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>
此处容器 div用于包含使用Google Chart库绘制的图表.这里我们使用google.charts.load方法加载最新版本的corecharts API.
Google Chart库使用非常使用json语法的简单配置.
// Instantiate and draw the chart. var chart = new google.visualization.PieChart(document.getElementById('container')); chart.draw(data, options);
此处数据表示json数据,而options表示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()方法用于添加列,其中第一个参数表示数据类型,第二个参数表示图例. 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] ]);
// Instantiate and draw the chart. var chart = new google.visualization.PieChart(document.getElementById('container')); chart.draw(data, options);
以下是完整示例 :
googlecharts_configuration.htm
<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);
验证结果.