我正在使用Google条形图,我一直坚持为各个条形添加颜色

问题描述

<!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>

current output

  1. 我正在使用条形图,它仅显示认的蓝色。
  2. 我使用了一个数组,该数组删除了没有数据(如0)的列
  3. 喜欢对数据进行排序
  4. 我要为每列显示单独的颜色
  5. 每个条形都像红色,绿色一样
  6. 我也喜欢添加注释
  7. 提前感谢

解决方法

在上面的注释中张贴的列标题和值似乎在这里可以正常工作...

唯一所做的更改...

  1. 为样式和注释角色添加type属性。
  2. 为样式角色添加了不同的颜色。

请参阅以下工作摘要...

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>