Google图表-更改条形的颜色

Eti*_*oël 2 html javascript google-visualization

我想更改条形图中每个条的颜色。目前,我尝试按照文档中的指定设置颜色选项:

var options = {
        'title' : results.title,
        'width' : 400,
        'height' : 300,
        'is3D' : true,
        'colors' : ["#194D86","#699A36", "#000000"],
        'allowHtml' : true
    }
Run Code Online (Sandbox Code Playgroud)

但这行不通。基本上,我希望下图中的每个条形都具有相同的颜色:http : //jsfiddle.net/etiennenoel/ZThMp/12/

有没有办法做到这一点,或者我必须更改代码结构才能做到这一点?

asg*_*ant 5

[编辑-下面的编辑中概述了一种更好的方法]

Visualization API按系列(或您希望的话,在DataTable中的列)为数据着色。解决方案是使用DataView将数据分成多个系列:

// get a list of all the labels in column 0
var group = google.visualization.data.group(data, [0], []);

// build the columns for the view
var columns = [0];
for (var i = 0; i < group.getNumberOfRows(); i++) {
    var label = group.getValue(i, 0);
    // set the columns to use in the chart's view
    // calculated columns put data belonging to each label in the proper column
    columns.push({
        type: 'number',
        label: label,
        calc: (function (name) {
            return function (dt, row) {
                return (dt.getValue(row, 0) == name) ? dt.getValue(row, 1) : null;
            }
        })(label)
    });
}
// create the DataView
var view = new google.visualization.DataView(data);
view.setColumns(columns);
Run Code Online (Sandbox Code Playgroud)

将图表中的“ isStacked”选项设置为“ true”,以解决导致的列间距问题,并使用视图而非DataTable绘制图表:

var chart = new google.visualization.ColumnChart(document.querySelector('#chart_div'));
chart.draw(view, {
    // options
    isStacked: true
});
Run Code Online (Sandbox Code Playgroud)

在这里查看示例。

[编辑:可视化API的更新中提供了新的(改进的)方法]

现在,您可以使用新的“样式”列角色来指定列的样式。它是这样的:

function drawChart() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Name');
    data.addColumn('number', 'Value');
    data.addColumn({type: 'string', role: 'style'});
    data.addRows([
        ['Foo', 5, 'color: #ac6598'],
        ['Bar', 7, 'color: #3fb0e9'],
        ['Baz', 3, 'color: #42c698']
    ]);

    var chart = new google.visualization.ColumnChart(document.querySelector('#chart_div'));
    chart.draw(data, {
        height: 400,
        width: 600,
        legend: {
            position: 'none'
        }
    });
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
Run Code Online (Sandbox Code Playgroud)

在此处查看示例:http : //jsfiddle.net/asgallant/gbzLB/