Google Visualization如何根据逻辑更改背景颜色柱形图

时间:2013-09-13 10:58:56

标签: charts logic google-visualization bar-chart

我的柱形图如下图所示。我想要优秀的酒吧绿色,因为它超过平均水平,非常好的蓝色和公平到红色。这可能吗?

根据条形图/单元格的值,我想更改柱形图的背景颜色

enter image description here

1 个答案:

答案 0 :(得分:2)

由于所有条形都按数据系列着色,因此您必须将条形图分成不同的系列,以使它们具有不同的颜色。您可以在DataView中使用计算列来完成此任务:

function drawChart() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Name');
    data.addColumn('number', 'Value');
    data.addRows([
        ['Foo', 2],
        ['Bar', 4],
        ['Baz', -3],
        ['Cud', 6],
        ['Waq', -8],
        ['Bat', -2],
        ['Cad', 5],
        ['Giv', 3],
        ['Muj', 9],
        ['Lof', -7],
        ['Duq', 5],
        ['Kaf', 1],
        ['Zij', 4]
    ]);

    var view = new google.visualization.DataView(data);
    // add as many different series as needed
    // make sure all possible values are covered, so you don't have any gaps where a data point can't be assigned to a series
    view.setColumns([0, {
        type: 'number',
        label: 'Value',
        calc: function (dt, row) {
            // if the value is less than 0, add to the red series
            return (dt.getValue(row, 1) < 0) ? dt.getValue(row, 1) : null;
        }
    }, {
        type: 'number',
        label: 'Value',
        calc: function (dt, row) {
            // if the value is greater than or equal to 0, add to the green series
            return (dt.getValue(row, 1) >= 0) ? dt.getValue(row, 1) : null;
        }
    }]);

    var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
    chart.draw(view, {
        legend: 'none',
        isStacked: true,
        height: 300,
        width: 800,
        // set the colors to use for the series (in the same order as the columns in the view)
        colors: ['red', 'green']
        /* or you can use the series.<series index>.color option to assign colors to specific series:
        series: {
            0: {
                color: 'red'
            },
            1: {
                color: 'green'
            }
        }
        */
    });
}
google.load('visualization', '1', {packages: ['corechart'], callback: drawChart});

在此处查看:http://jsfiddle.net/asgallant/dMWWk/