为Google图表中的每个条指定不同的颜色

时间:2011-10-29 09:47:58

标签: javascript google-visualization

我正在尝试为柱状图中的每个条形指定不同的颜色,但是当我尝试每个条形图获得相同的颜色时。

代码:

  // Load the Visualization API and the piechart package.
  google.load('visualization', '1.0', {'packages':['corechart']});

  // Set a callback to run when the Google Visualization API is loaded.
  google.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', 'Something');
  data.addColumn('number', 'Numbers');
  data.addRows([
    ['A', 40],
    ['B', 17],
    ['C', 7]
  ]);

  // Set chart options
  var options = {'title':'Megafon 27/10 2011',
                 'width':1300,
                 'height':600,
         'colors' : ['red', 'blue', 'green']
        };

  // Instantiate and draw our chart, passing in some options.
  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
  chart.draw(data, options);
}

我知道这可能很容易,但是现在我看不到它。请帮帮我。

谢谢

拉​​斯

1 个答案:

答案 0 :(得分:4)

更改为:

...
// Create the data table.
var data = new google.visualization.DataTable();

var raw_data = [
    ['A', 40],
    ['B', 17],
    ['C', 7]
];

data.addColumn('string', 'Columns');
for (var i = 0; i  < raw_data.length; ++i) {
    data.addColumn('number', raw_data[i][0]);
}
data.addRows(1);
data.setValue(0, 0, 'row');
for (var i = 0; i  < raw_data.length; ++i) {    
    data.setValue(0, i+1, raw_data[i][1]);
}

// Set chart options
...

=== UPDATE ===

简化版:

...
// Create the data table.
var data = new google.visualization.DataTable();

var raw_data = {
    'A':   40
    , 'B': 17
    , 'C':  7
};

data.addRows(1);
var i = 0;
for (var index in raw_data) {
    data.addColumn('number', index);
    data.setValue(0, i++, raw_data[index]);
}

// Set chart options
...