<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>
选项
每个图表都有许多可定制的选项,包括标题、颜色、线条粗细、背景填充等等。尽管图表工具团队在默认图表外观上做了很多工作,但是您可能想要自定义图表,例如添加title或axis标签。
通过使用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或选项中指定图表大小,则可能无法正确呈现图表。