问题描述
<!DOCTYPE html>
<html lang="en-US">
<body>
<h1>My Web Page</h1>
<div id="piechart"></div>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load google charts
google.charts.load('current',{'packages':['corechart']});
google.charts.setonLoadCallback(drawChart);
// Draw the chart and set the chart values
var a = [['Work',8],['Eat',2],['TV',4],['Gym',['Sleep',['walk',['games',['chess',['drink',['dance',6]];
a.sort(compareSecondColumn);
function compareSecondColumn(a,b) {
if (a[1] === b[1]) {
return 0;
}
else {
return (a[1] > b[1]) ? -1 : 1;
}
}
// Draw the chart and set the chart values
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task','Hours per Day'],a[0],a[1],a[2],a[3],a[4]
]);
// Optional; add a title and set the width and height of the chart
var options = { 'title': 'the title','width': 550,'height': 400 };
// display the chart inside the <div> element with id="piechart"
var chart = new google.visualization.ColumnChart(document.getElementById('piechart'));
chart.draw(data,options);
}
</script>
</body>
</html>
解决方法
在上面的注释中张贴的列标题和值似乎在这里可以正常工作...
唯一所做的更改...
- 为样式和注释角色添加
type
属性。 - 为样式角色添加了不同的颜色。
请参阅以下工作摘要...
var a = [['Work',8,"#E53935",8],['Eat',2,"#1E88E5",2],['TV',4,"#43A047",4]];
a.sort(compareSecondColumn);
function compareSecondColumn(a,b) {
if (a[1] === b[1]) {
return 0;
}
else {
return (a[1] > b[1]) ? -1 : 1;
}
}
google.charts.load('current',{
packages: ['corechart']
}).then(function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task','Hours per Day',{role: 'style',type: 'string'},{role: 'annotation',type: 'number'}],a[0],a[1],a[2]
]);
var options = {
title: 'the title',width: 550,height: 400,legend: 'none'
};
var chart = new google.visualization.ColumnChart(document.getElementById('piechart'));
chart.draw(data,options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart"></div>