简体   繁体   English

Google柱形图:如何更改带有负值的列的颜色

[英]Google column chart: how to change the color of columns with negative values

I am trying to create a column chart and I want the columns to be red when their value is negative. 我正在尝试创建一个柱形图,并且当它们的值为负时,我希望这些柱为红色。 Here is my function: 这是我的功能:

function drawChartFlows(data, title, id) {

if (googleAPILoaded != true)
    return;

var array = new google.visualization.DataTable();
array.addColumn('number', 'months');
array.addColumn('number', 'flows');
var flows = dataToArray(data);
var series = [];
for (var it = 0; it < flows.length; it++) {
    var flow = Number(flows[it]);
    if (flow <= 0) {
        series[it] = 'red';
        array.addRow([it, (flow*(-1))]);
    } else {
        series[it] = 'blue';
        array.addRow([it, flow]);
    }
}
var options = {
        title: 'Cash flows for '+title,
        width: 1400,
        height: 800,
        legend: { position: 'none' },
        chart: { subtitle: 'monthly flows' },
        axes: {
            x: {
                0: { side: 'top', label: 'Cash flows'}
            }
        },
        bar: { groupWidth: "50%" },
        colors: series
};

var chart = new google.visualization.ColumnChart($(id)[0]);
chart.draw(array, options); 
}

The columns are displayed correctly, but they are all blue. 列正确显示,但是它们都是蓝色的。 I noticed that the color of all the columns depends on the color in series[0]. 我注意到所有列的颜色取决于series [0]中的颜色。 If series[0] is 'blue', all the columns are blue, no matter what color I put in the other slots of series[]. 如果series [0]为'blue',则无论我在series []的其他插槽中放置什么颜色,所有列均为蓝色。

What did I do wrong ? 我做错了什么 ? Thank you in advance ! 先感谢您 !

use a style Column Role 使用样式列角色

array.addColumn('number', 'months');
array.addColumn('number', 'flows');
array.addColumn({role: 'style', type: 'string'});

then... 然后...

if (flow <= 0) {
    array.addRow([it, (flow*(-1)), 'color: red;']);
} else {
    array.addRow([it, flow, 'color: blue;']);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM