<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 }
使用这些值更新上例中的 options 对象,以了解它们对图表的影响。
指定图表大小
一种很常见的设置选项是图表高度和宽度。您可以在两个位置指定图表大小:在容器 <div>
元素的 HTML 中,或在图表选项中指定。如果您在这两个位置都指定了尺寸,则图表通常会采用 HTML 中指定的尺寸。如果您未在 HTML 中或作为选项指定图表尺寸,则图表可能无法正确呈现。
在其中一个位置指定尺寸有诸多优势:
- 在 HTML 中指定大小 - 图表可能需要几秒钟的时间来加载和呈现。如果您已经在 HTML 中设置了图表容器的大小,那么页面布局在图表加载后不会发生跳动。
- 指定图表大小选项 - 如果图表大小使用 JavaScript,则您可以复制和粘贴 JavaScript,或者序列化、保存和恢复 JavaScript,并使图表的大小保持一致。