<html> <head> <!--Load the AJAX API--> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.charts.load('current', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.charts.setOnLoadCallback(drawChart); // Callback that creates and populates a data table, // instantiates the pie chart, passes in the data and // draws it. function drawChart() { // Create the data table. var data = new google.visualization.DataTable(); data.addColumn('string', 'Topping'); data.addColumn('number', 'Slices'); data.addRows([ ['Mushrooms', 3], ['Onions', 1], ['Olives', 1], ['Zucchini', 1], ['Pepperoni', 2] ]); // Set chart options var options = {'title':'How Much Pizza I Ate Last Night', 'width':400, 'height':300}; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.PieChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> </head> <body> <!--Div that will hold the pie chart--> <div id="chart_div" style="width:400; height:300"></div> </body> </html>
指定选项
每个图表都有许多可自定义的选项,包括标题、颜色、线条粗细、背景填充等。虽然图表工具团队一直致力于打造默认图表外观,但您可能需要自定义图表,例如添加标题或轴标签。
通过定义具有 option_name/option_value 属性的 JavaScript 对象,为图表指定自定义选项。请使用图表文档中列出的选项名称。每个图表的文档都列出了一组可自定义的选项。例如,饼图提供的选项包括“legend”、“title”和“is3D”。所有选项都有记录的默认值。
以下对象定义了图例位置、图表标题、图表大小和饼图的 3D 选项:
var options = { 'legend':'left', 'title':'My Big Pie Chart', 'is3D':true, 'width':400, 'height':300 }
使用上述示例更新上述选项中的对象,以查看这些值对图表有何影响。
指定图表大小
一种很常见的设置方式就是设置图表高度和宽度。您可以在两个位置指定图表大小:在容器 <div>
元素的 HTML 中,或在图表选项中。如果您同时在两个位置指定了尺寸,则图表通常会遵循 HTML 中指定的尺寸。如果您未在 HTML 中或将图表尺寸指定为选项大小,则图表可能会无法正确呈现。
在一个位置指定尺寸有诸多好处:
- 在 HTML 中指定尺寸 - 加载图表可能需要花费几秒钟时间。如果您的图表容器已采用 HTML 尺寸,那么在页面加载该图表时,页面布局不会发生跳转。
- 将尺寸指定为图表选项 - 如果图表尺寸采用 JavaScript,您可以复制并粘贴 JavaScript,或者对 JavaScript 进行序列化、保存和恢复,并调整图表的大小。