如何在柱形图中为条形添加不同的颜色

时间:2017-10-26 12:41:07

标签: javascript charts google-visualization column-chart

如何在柱形图中为条形添加不同的颜色。在选项中添加颜色字段不起作用。请帮忙。

以下是代码段:

tdata.addRow([col1, arr[0].Manual])
        tdata.addRow([col2, arr[0].Auto]);
        tdata.addRow([col3, arr[0].Amount]);

        options = {
            fontSize: 12,
            height: 430,
            width: 380,
            chartArea: { left: "25%", top: "20%", right: "5%", bottom: "10%" },
            backgroundColor: '#f5f5f5',
            title: 'Project',
            pieSliceText: 'value',
            colors: ['red', 'green', 'blue'],
            'is3D': true
        };
        var chart = new google.visualization.ColumnChart(document.getElementById('drilldown_div'));
        chart.draw(tdata, options);
        return false;

2 个答案:

答案 0 :(得分:3)

colors选项将颜色应用于每个系列 所以如果你有3种颜色
你需要3个y轴列

如下......

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y0', 'y1', 'y2'],
    ['A', 100, 120, 130]
  ]);

  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
  chart.draw(data, {
    colors: ['red', 'green', 'blue']
  });
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

为系列中的各列着色,
使用'style'列角色

如下......

注意:使用'style'列角色会使图例无效

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y', {role: 'style', type: 'string'}],
    ['A', 100, 'red'],
    ['B', 120, 'green'],
    ['C', 130, 'blue']
  ]);

  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
  chart.draw(data, {
    legend: 'none'
  });
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

答案 1 :(得分:0)

这是根据谷歌文档的答案,使用颜色属性而不是背景颜色。

var options = {   width: 400,   height: 240,   title: 'Toppings I Like On My Pizza',   colors: ['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6'] };

chart.draw(data, options);

you can find more here