How can I add different colors to bar in Column chart

我只是一个虾纸丫 提交于 2019-12-30 23:58:40

问题


How can i add different colors to Bars in Column chart. Adding colors field in option is not working. Please help.

Below is the code snippet:

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;

回答1:


the colors option applies colors to each series
so if you have 3 colors
you would need 3 y-axis columns

as follows...

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>

to color individual columns within a series,
use a 'style' column role

as follows...

note: using a 'style' column role will invalidate the legend

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>



回答2:


This is answer according to google document, use color property instead of background color.

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



来源:https://stackoverflow.com/questions/46954630/how-can-i-add-different-colors-to-bar-in-column-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!